Web & Mobile Development
jQuery in 2026: Reading, Maintaining and Retiring a Legacy Codebase
Beginner8 min readUpdated
jQuery still runs on a large share of the web, so most developers meet it in maintenance rather than in greenfield work. This guide explains the model behind the dollar function, covers selection, manipulation, events, Ajax and plugins with real examples, then gives an idiom-by-idiom mapping to the platform APIs that replaced it and a staged plan for removing the dependency without a rewrite.
What you will learn
- Explain the problems jQuery solved and why they mostly no longer exist
- Read jQuery code fluently — the wrapped set, chaining, traversal, events and Ajax
- Recognise the plugin and namespacing patterns used in older codebases
- Translate common jQuery idioms into equivalent standard DOM APIs
- Plan an incremental removal that keeps a legacy application shippable throughout
For roughly a decade, adding jQuery was the first line of nearly every web project. The library did not offer a new architecture or a component model; it offered relief. Browsers of that era disagreed about almost everything — event registration, opacity, XMLHttpRequest, whether getElementsByClassName existed — and jQuery hid those differences behind one concise API that worked identically everywhere. That was enough to make it the most widely deployed JavaScript library ever written.
Most developers now encounter it the other way round: inheriting a codebase where it is load-bearing. This guide is written for that situation. It explains the model well enough that you can read jQuery confidently, covers the parts you will actually meet — selection, DOM work, events, Ajax, plugins — and then maps each idiom onto the standard API that superseded it, with a staged plan for getting the dependency out without stopping feature work.
The problems it solved, and where they went
Three things made jQuery indispensable, and all three have since been absorbed by the platform.
Browser normalisation. Attaching an event once required branching between addEventListener and attachEvent; the event object itself had different property names. jQuery smoothed that over. Modern browsers, including the evergreen ones that replaced the fixed-version era, implement the same standards.
Terse selection. Before querySelectorAll, finding elements by CSS selector meant writing your own engine or shipping one. jQuery bundled Sizzle, and the dollar function became shorthand for "find these elements". The DOM gained the same capability natively in 2009 and it is now universally available.
A usable Ajax layer. Raw XMLHttpRequest was verbose and callback-heavy. $.ajax wrapped it, added JSON handling and, later, a promise-like interface. fetch with async/await is both shorter and better specified.
What jQuery never provided is what most applications actually need today: a way to keep the DOM synchronised with application state. That gap is why the community moved to component frameworks rather than to a better jQuery.
The wrapped set, and why everything chains
Almost all jQuery code is built on one idea. Calling $(selector) returns a wrapped set: an array-like object holding zero or more DOM elements, decorated with every jQuery method. Methods operate on the whole set at once — no loop needed — and most of them return the set again, which is what makes chaining work.
$(".row.expired")
.addClass("dimmed")
.attr("aria-hidden", "true")
.find("button")
.prop("disabled", true);
The crucial asymmetry: setters return the set, getters do not. $(".row").text("hi") sets the text of every matched row and returns the set; $(".row").text() reads the text of the first element only and returns a string, ending the chain. Reading unfamiliar jQuery is largely a matter of tracking where a chain silently becomes a value.
A wrapped set with no matches is not an error. $(".typo").hide() does nothing and reports nothing, which is convenient and is also why typos in selectors can survive for years. Check .length when a match is required.
The dollar function is overloaded four ways: a selector string, a DOM element or set to wrap, an HTML string to parse into new nodes, and — the one that trips people up — a function, which registers it to run when the document is ready. $(function () { ... }) is the same as $(document).ready(...).
Selecting, traversing and filtering
Selectors are CSS, plus a set of jQuery-only extensions such as :visible, :contains() and :first. Those extensions cannot be delegated to the browser engine, so they are markedly slower and have no standard equivalent — worth noting when you plan a migration.
const $rows = $("#orders tbody tr");
$rows.first(); // first element, still wrapped
$rows.filter(".pending"); // narrow the set
$rows.not(".archived"); // exclude
$rows.eq(2); // by index
$rows.find("td.amount"); // descendants of the set
$row.closest("form"); // nearest matching ancestor
$row.siblings().addBack(); // siblings plus the original
$el.parent().children(".error");
Traversal methods are the part of jQuery whose expressiveness the standard DOM still does not fully match; closest is native now, but there is no built-in siblings() or addBack(). Those are three-line helpers when you need them.
Repeated selection is the classic performance mistake. $(".item") re-runs the query every time, so cache the result in a variable — the near-universal convention of prefixing such variables with a dollar sign exists precisely to signal "this is a wrapped set, not an element".
Changing the document
$el.addClass("open").removeClass("closed").toggleClass("pinned", isPinned);
$el.hasClass("open");
$el.text("Plain text, escaped");
$el.html("<em>parsed as markup</em>");
$el.val(); // form control value
$el.attr("data-state", "ready"); // HTML attribute
$el.prop("checked", true); // live DOM property
$el.data("orderId"); // reads data-order-id, with a cache
$list.append($row); // insert last inside
$row.before($banner); // insert as previous sibling
$row.remove(); // detach and clean up handlers/data
Two distinctions matter when debugging. attr reads and writes the HTML attribute; prop reads and writes the live property. For a checkbox, attr("checked") reflects the markup as authored while prop("checked") reflects what the user has actually done — mixing them up produces forms that submit stale values. And .data() does not simply read the data-* attribute: it initialises from the attribute once and then keeps values in an internal cache, so later attribute changes are invisible to it.
.html() parses and inserts markup, which makes it a cross-site-scripting vector whenever the string contains anything a user supplied. Use .text() unless you control every byte.
Events and delegation
$("#save").on("click", function (event) {
event.preventDefault();
console.log($(this).data("orderId")); // this is the raw DOM element
});
// Delegated: one handler on a stable ancestor, works for rows added later.
$("#orders").on("click", ".row .delete", function () {
$(this).closest(".row").remove();
});
$("#save").off("click");
$("#form").trigger("submit");
$el.one("transitionend", finish); // fires at most once
Inside a handler, this is the raw element, not a wrapped set, so $(this) is the standard first line. That also means arrow functions break the idiom — a real hazard when modernising a file, since converting handlers to arrows silently changes this to the enclosing scope.
Delegation is jQuery's most valuable event feature and it transfers directly to modern code: the handler lives on a container that always exists, and the selector is matched as the event bubbles. That is why dynamically inserted rows keep working without rebinding.
The library also normalises event.which, pageX/pageY and similar properties, and it supports custom events with trigger and namespaced handlers such as "click.editor", which let a plugin remove only its own listeners with .off(".editor").
Ajax
$.ajax({
url: "/api/orders",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ sku: "A-12", qty: 2 }),
dataType: "json",
})
.done((data) => renderOrder(data))
.fail((jqXHR, textStatus) => showError(jqXHR.status, textStatus))
.always(() => hideSpinner());
$.getJSON("/api/health", render); // shorthand
$("#results").load("/partials/results"); // fetch HTML into an element
Two behaviours differ from fetch and matter when you port code. jQuery treats any non-2xx response as a failure and calls fail, whereas fetch resolves and leaves you to check response.ok. And jQuery serialises a plain data object into form encoding by default; sending JSON requires setting contentType and stringifying yourself. When you are inspecting what a legacy endpoint actually returns, the JSON formatter and the URL encoder/decoder save a lot of squinting at devtools.
$.Deferred objects predate native promises and are not fully compliant with them, though modern jQuery makes them interoperable enough to await. In older code you will also meet $.when(a, b).then(...), the ancestor of Promise.all.
The plugin pattern, and other idioms of the era
Plugins extend $.fn, the prototype shared by every wrapped set. The conventional shape looks like this:
(function ($) {
"use strict";
$.fn.tooltip = function (options) {
const settings = $.extend({ delay: 200, position: "top" }, options);
return this.each(function () { // preserve chaining
const $el = $(this);
if ($el.data("tooltip-bound")) return; // idempotent
$el.data("tooltip-bound", true).on("mouseenter.tooltip", () => show($el, settings));
});
};
})(jQuery);
The immediately invoked function expression gives the plugin a private scope and guarantees that $ means jQuery even on a page running noConflict(). return this.each(...) is what keeps the chain alive. $.extend merges defaults with caller options — the ancestor of object spread.
Alongside plugins you will see other period idioms: a single global namespace object holding every function, $(document).ready wrappers nested several deep, feature flags read from data-* attributes, and handlers registered inline in the HTML. None of this is wrong, but it predates modules, so understanding load order is often the hardest part of reading such a codebase. The JavaScript fundamentals guide covers the module and scope features that replaced these conventions.
Idiom-by-idiom, in plain DOM
| jQuery | Standard DOM |
|---|---|
$(".item") | document.querySelectorAll(".item") |
$("#id") | document.getElementById("id") |
$el.find(".x") | el.querySelectorAll(".x") |
$el.closest("form") | el.closest("form") |
$el.addClass("a").removeClass("b") | el.classList.add("a"); el.classList.remove("b") |
$el.attr("x", v) / $el.prop("checked", v) | el.setAttribute("x", v) / el.checked = v |
$el.text(s) / $el.html(s) | el.textContent = s / el.innerHTML = s |
$el.data("orderId") | el.dataset.orderId |
$parent.append($child) | parent.append(child) |
$el.remove() | el.remove() |
$el.on("click", fn) | el.addEventListener("click", fn) |
$parent.on("click", ".row", fn) | listener on parent plus event.target.closest(".row") |
$.ajax(...) / $.getJSON(url) | fetch(url) then await response.json() |
$.extend({}, a, b) | object spread |
$.each(arr, fn) / $.map | arr.forEach(fn) / arr.map(fn) |
$(fn) | document.addEventListener("DOMContentLoaded", fn) or a deferred script |
$el.hide() / $el.show() | toggle a CSS class |
$el.fadeIn() | a CSS transition, or the Web Animations API |
The one row without a clean equivalent is delegation, and it is short enough to write once:
function delegate(root, type, selector, handler) {
root.addEventListener(type, (event) => {
const match = event.target.closest(selector);
if (match && root.contains(match)) handler.call(match, event);
});
}
Getting it out, without a rewrite
A big-bang removal on a large codebase is rarely justified. A staged approach keeps the application releasable at every step.
- Inventory first. Grep for
$(and for$.separately, and list the plugins. The plugins usually decide the schedule: a bespoke tooltip is an afternoon, a date picker or grid used on forty screens is a project of its own. - Delete the dead weight. Older bundles often include jQuery UI, jQuery Migrate or several plugins for features nobody uses any more. Removing unused code is the cheapest byte saving available and reduces the surface you must port.
- Establish a boundary. New work uses standard APIs and modules; existing files stay as they are. Add a lint rule that forbids
$in new directories so the line does not blur. - Convert by file, not by idiom. Porting all
.addClass()calls across fifty files produces an unreviewable diff. Take one screen, convert it end to end, and ship it. - Replace plugins with platform features. Native
dialogreplaces modal plugins,detailsreplaces accordions, CSS transitions replace the animation queue, and the Intersection Observer replaces scroll-position plugins. - Remove the script tag last, once the inventory is empty, and confirm with a scan for
jQueryand$in the built output. Measure before and after; the byte savings and reduced parse cost are usually visible in the metrics discussed in application performance.
If the application is an AngularJS one with jQuery mixed in, sequence the work carefully — the framework migration and the library removal interact, and the trade-offs are set out in migrating from AngularJS to Angular.
Key takeaways
- jQuery solved browser normalisation, terse selection and Ajax ergonomics; the platform now does all three, so new projects gain nothing from it while existing ones still depend on it heavily.
- Everything revolves around the wrapped set: methods act on every match, setters return the set to allow chaining, and getters read only the first element.
- Know the pairs that cause bugs —
attrversusprop,.text()versus.html(), and.data()reading from a cache rather than the attribute. - Delegated handlers bound to a stable ancestor are the pattern worth carrying forward; inside a handler
thisis the raw element, so arrow functions change the meaning of the code. - Nearly every idiom has a one-line standard equivalent; delegation is the only gap and a ten-line helper closes it.
- Remove the dependency file by file behind a lint boundary, deal with plugins first because they dictate the schedule, and drop the script tag only when the inventory is empty.
Sources and further reading
Frequently asked questions
- Is jQuery dead?
- It is not dead, but it is finished as a default choice. The library is still maintained and still loads on a very large number of production sites, so knowing it is a practical maintenance skill. What has changed is that its three original selling points — cross-browser normalisation, terse selection and a usable Ajax wrapper — are all handled by the platform now, so a new project gains nothing by adding it.
- Can I use jQuery alongside a modern framework?
- You can, and hybrid pages do exist, but treat it as a temporary state. Frameworks own the DOM they render, and jQuery mutating those same nodes behind their back leads to state that the framework does not know about and re-renders that silently discard your changes. If both must coexist, confine jQuery to regions the framework never touches and delete it region by region.
- Why does jQuery return the same object from almost every method?
- Most jQuery methods return the wrapped set they were called on, which is what makes chaining possible. Setters return the set so the next call continues on the same elements; getters break the chain and return a plain value read from the first element only. That asymmetry is the single most common source of confusion when reading unfamiliar jQuery code.
- How much smaller is a page without jQuery?
- The minified and compressed library is roughly 30 KB, plus parse and execute time on every page load, plus whatever plugins ride on top of it — those are often larger than the library itself. On a content site with a handful of interactions the entire dependency typically replaces about fifty lines of standard DOM code, so removal is usually a clear win for both load time and dependency surface.