Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 56 ยท Migration and Performance

From jQuery to Modern JavaScript

Translate common jQuery tasks into plain modern JavaScript: selecting, classes, events, delegation, attributes, fetch, animation. Learn when to keep jQuery.

jQuery was created to smooth over browser differences and to make the DOM pleasant to use. Today the browsers agree with each other, and the DOM has absorbed many of jQuery's best ideas: querySelectorAll(), classList, addEventListener(), fetch(), promises and the Web Animations API. For many tasks you can now reach the same result with no library at all.

This lesson is a translation guide. For each task you already know in jQuery, you will see the plain JavaScript version next to it, run both on the same page, and learn the small differences that cause bugs. It also helps you decide honestly when keeping jQuery is the better choice. The lessons on selecting elements and events give the jQuery side in full.

What the browser absorbed

Selectors querySelector and querySelectorAll
Classes classList.add, remove, toggle
Events addEventListener with delegation
Network fetch and promises
1 / 2

Selecting and looping

$(".item") returns a collection, even when nothing matches. document.querySelectorAll(".item") returns a static NodeList, also possibly empty. Both support .length. The key difference is looping. jQuery methods apply to every element automatically (implicit iteration); with the DOM you loop yourself.

JavaScript
// jQuery
$(".item").addClass("on");

// Modern JavaScript
document.querySelectorAll(".item").forEach((el) => el.classList.add("on"));

NodeList has forEach(), entries() and iteration with for...of, but not map() or filter(). Convert with Array.from(list) or [...list] when you need them. For a single element use document.querySelector(), which returns null when nothing matches, so a missing element throws on the next property access. In jQuery you never had to check; in plain code, el?.classList.add("on") or an if is your guard.

Traversal has native counterparts too: el.closest(".card") replaces .closest(), el.parentElement replaces .parent(), el.children replaces .children(), el.nextElementSibling replaces .next(), and el.matches(".x") replaces .is(".x").

Classes, text, attributes and styles

Task jQuery Plain JavaScript
Add a class $el.addClass("a") el.classList.add("a")
Toggle with a flag $el.toggleClass("a", on) el.classList.toggle("a", on)
Has class $el.hasClass("a") el.classList.contains("a")
Read text $el.text() el.textContent
Set text $el.text("x") el.textContent = "x"
Set HTML $el.html(s) el.innerHTML = s
Attribute $el.attr("href") el.getAttribute("href")
Property $el.prop("checked") el.checked
Data $el.data("id") el.dataset.id
Style $el.css("color", "red") el.style.color = "red"
Remove $el.remove() el.remove()
Append $el.append(child) el.append(child)
Value $input.val() input.value

Two details matter. dataset always returns strings: jQuery's .data() converts "42" to a number and "true" to a boolean, while dataset.id stays "42". And .css("width") on jQuery returns the computed value, whereas el.style.width only reads inline styles; use getComputedStyle(el).width for the real value.

Same task, two ways

Events and delegation

.on("click", fn) becomes addEventListener("click", fn). The handler receives the native Event, so the jQuery event helpers disappear: event.preventDefault() and event.stopPropagation() are native already. Inside a handler this is the element in both cases, but arrow functions have no this, so use event.currentTarget.

Delegation, which the delegation lesson explores, needs a few more lines. jQuery's $("#list").on("click", ".item", fn) filters by selector for you. In plain code you listen on the parent and test the target yourself:

JavaScript
document.querySelector("#list").addEventListener("click", (event) => {
  const item = event.target.closest(".item");
  if (!item || !event.currentTarget.contains(item)) return;
  item.classList.toggle("on");
});

Using closest() rather than comparing event.target directly keeps working when the item contains inner elements such as a <span> or an icon. The contains() check stops matches from outside the list when delegated handlers are nested.

Other event differences: native listeners removed with removeEventListener() need the same function reference (jQuery's .off() can remove by event name or namespace), and one-time handlers use the option { once: true }. Custom events use new CustomEvent("name", { detail: data }) with dispatchEvent(), which replaces .trigger() with extra parameters.

One list, two delegated handlers

AJAX becomes fetch

$.getJSON(url) becomes fetch(url).then((r) => r.json()). The big trap is error handling. fetch() only rejects on network failures. A 404 or 500 response still resolves, so you must check response.ok yourself. jQuery treated those statuses as failures and called .fail().

JavaScript
async function loadJson(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error("HTTP " + response.status);
  }
  return response.json();
}

Form data is sent with new FormData(form) or JSON.stringify() plus a Content-Type header, and query strings come from new URLSearchParams(object), replacing $.param(). Timeouts use AbortSignal.timeout(5000). Because the lesson page cannot reach a real server, the next example builds a Response object by hand, which is exactly what fetch() resolves with. The AJAX promises lesson shows the jQuery side in more detail.

Handling fetch responses, including errors

Animation: let CSS do the work

.fadeIn(), .slideUp() and .animate() move styles with JavaScript timers. The browser does it better. For simple state changes, toggle a class and describe the motion with a CSS transition, which runs off the main thread and respects prefers-reduced-motion when you add a media query. For sequences and finer control, element.animate(keyframes, options) from the Web Animations API returns an Animation object with a finished promise, the equivalent of jQuery's completion callback.

jQuery Plain approach
.fadeOut(300) transition: opacity .3s plus a class
.slideToggle() transition on max-height or grid-template-rows
.animate({ left: 200 }, 400) el.animate({ left: "200px" }, 400)
complete callback animation.finished.then(...)
.stop() animation.cancel() or .pause()
CSS transition and Web Animations

When to keep jQuery

Rewriting working code has a cost, so it is not always the right move. Keep jQuery when:

  • the page already depends on it through a plugin, a theme or a framework such as an older Bootstrap or WordPress admin screen;
  • the code is stable, well tested and rarely edited;
  • you rely on many cross-element helpers, such as .serialize(), .animate() queues or a plugin ecosystem.

Choose plain JavaScript for new code, small pages and anything where an extra 30 KB matters. A middle path is common: leave existing jQuery code alone, and write new features without it, so the dependency shrinks over time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does document.querySelector(".missing") return when nothing matches?

    querySelector returns null for no match, so accessing a property on it throws. jQuery returns an empty collection that silently ignores calls.
  2. 2. A server answers a fetch() request with status 404. What happens?

    fetch only rejects for network-level failures. HTTP error statuses resolve normally, so you must check response.ok yourself.
  3. 3. Why use event.target.closest("li") in a delegated listener?

    event.target is the innermost element clicked. closest() climbs to the matching ancestor, so inner spans and icons do not break the handler.
  4. 4. How does el.dataset.id differ from jQuery's .data("id") for data-id="42"?

    dataset values are strings. jQuery's .data() converts numeric and boolean-looking values, which is a common source of subtle bugs when porting.
  5. 5. Which is a good reason to keep jQuery in a project?

    Existing dependencies and stable code are valid reasons. Native APIs cover selecting, events and networking well, so new code rarely needs the library.

Summary

  • querySelectorAll() plus forEach() replaces $() with implicit iteration; remember null from querySelector() for missing elements.
  • classList, textContent, dataset, getAttribute() and style match the jQuery getters and setters, with dataset returning strings only.
  • Delegation in plain code means listening on a parent and calling event.target.closest(selector).
  • fetch() resolves for HTTP errors, so check response.ok; use URLSearchParams, FormData and AbortSignal.timeout() for the rest.
  • Prefer CSS transitions and element.animate() to timer-based jQuery effects.
  • Keep jQuery where plugins or stable legacy code need it; write new features without it.

Next: Best Practices, Performance and Pitfalls.