TExcelTAD
Home › jQuery › jQuery vs Modern JavaScript

jQuery vs Modern JavaScript

When jQuery appeared, plain DOM code was verbose and different in every browser. Since then, many of jQuery's best ideas were added to the web platform itself. This lesson puts the most common jQuery operations side by side with their vanilla JavaScript equivalents, so you can read both styles and choose consciously.

Selecting elements

jQuery Modern JavaScript
$("#menu") document.getElementById("menu") or document.querySelector("#menu")
$(".item") document.querySelectorAll(".item") (a static NodeList)
$el.find("a") el.querySelectorAll("a")
$el.closest(".card") el.closest(".card")
$el.parent(), $el.children() el.parentElement, el.children
$el.next(), $el.prev() el.nextElementSibling, el.previousElementSibling
$el.is(".active") el.matches(".active")

The big difference: jQuery methods work on a whole set automatically. Vanilla code works on one element, so applying something to many elements needs a loop, e.g. document.querySelectorAll(".item").forEach(el => …).

Side by side: the same widget twice

Both halves implement the same thing — a list where clicking an item toggles it and a button adds a new item. Compare the code.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 13px; display: flex; gap: 16px; }
    section { flex: 1; border: 1px solid #ccc; border-radius: 6px; padding: 0 10px 10px; }
    li { cursor: pointer; }
    li.done { text-decoration: line-through; color: #999; }
  </style>
</head>
<body>
  <section id="jq">
    <h4>jQuery</h4>
    <ul><li>Milk</li><li>Bread</li></ul>
    <button>Add</button>
  </section>
  <section id="vanilla">
    <h4>Vanilla JS</h4>
    <ul><li>Milk</li><li>Bread</li></ul>
    <button>Add</button>
  </section>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    // ---------- jQuery ----------
    $("#jq ul").on("click", "li", function () {
      $(this).toggleClass("done");
    });
    $("#jq button").on("click", function () {
      $("<li>").text("Item " + ($("#jq li").length + 1)).hide().appendTo("#jq ul").fadeIn(200);
      console.log("jQuery items:", $("#jq li").length);
    });

    // ---------- Vanilla JS ----------
    const list = document.querySelector("#vanilla ul");
    list.addEventListener("click", (e) => {
      const li = e.target.closest("li");
      if (li && list.contains(li)) li.classList.toggle("done");
    });
    document.querySelector("#vanilla button").addEventListener("click", () => {
      const li = document.createElement("li");
      li.textContent = "Item " + (list.children.length + 1);
      list.append(li);
      li.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200 });
      console.log("vanilla items:", list.children.length);
    });
  </script>
</body>
</html>

Classes, attributes, content and styles

jQuery Modern JavaScript
$el.addClass("a") / removeClass / toggleClass el.classList.add("a") / remove / toggle
$el.hasClass("a") el.classList.contains("a")
$el.text() / $el.text("x") el.textContent / el.textContent = "x"
$el.html("<b>x</b>") el.innerHTML = "<b>x</b>"
$el.val() el.value
$el.attr("href") / $el.attr("href", u) el.getAttribute("href") / el.setAttribute("href", u)
$el.prop("checked") el.checked
$el.data("userId") el.dataset.userId (always a string)
$el.css("color", "red") el.style.color = "red"
$el.css("color") (computed) getComputedStyle(el).color
$el.hide() / $el.show() el.hidden = true / false (or toggle a class)

Creating, inserting and removing

jQuery Modern JavaScript
$("<li>").text("x") const li = document.createElement("li"); li.textContent = "x";
$parent.append(child) / prepend parent.append(child) / parent.prepend(child)
$el.after(x) / $el.before(x) el.after(x) / el.before(x)
$el.remove() el.remove()
$el.empty() el.replaceChildren()
$el.clone() el.cloneNode(true)
$el.replaceWith(x) el.replaceWith(x)

Events

jQuery Modern JavaScript
$(fn) document.addEventListener("DOMContentLoaded", fn) or a defer script
$el.on("click", fn) el.addEventListener("click", fn)
$el.off("click", fn) el.removeEventListener("click", fn)
$el.one("click", fn) el.addEventListener("click", fn, { once: true })
$p.on("click", "li", fn) p.addEventListener("click", e => { const li = e.target.closest("li"); if (li) … })
$el.trigger("my:event", [data]) el.dispatchEvent(new CustomEvent("my:event", { detail: data, bubbles: true }))
.on("click.ns") / .off(".ns") addEventListener(…, { signal }) + AbortController.abort()

AJAX, effects and utilities

jQuery Modern JavaScript
$.getJSON(url) fetch(url).then(r => r.json())
$.post(url, data) fetch(url, { method: "POST", body: new URLSearchParams(data) })
$.ajax({ … JSON … }) fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(obj) })
$.when(a, b) Promise.all([a, b])
$el.fadeIn() / .animate() CSS transitions, or el.animate(keyframes, options) (Web Animations API)
$.each(arr, fn) arr.forEach(fn)
$.map / $.grep arr.map / arr.filter
$.extend({}, a, b) { ...a, ...b } (shallow)
$.param(obj) new URLSearchParams(obj).toString()

Note: fetch does not reject on HTTP errors like 404 or 500 — only on network failures. Check response.ok yourself. jQuery's AJAX fails on any non-2xx status.

html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
  <button id="go">Load with both</button>
  <pre id="out"></pre>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const url = "data:application/json," + encodeURIComponent(JSON.stringify({ user: "Ana", points: 42 }));

    $("#go").on("click", async function () {
      // jQuery
      $.getJSON(url).done(data => console.log("jQuery:", data));

      // fetch + async/await
      try {
        const response = await fetch(url);
        if (!response.ok) throw new Error("HTTP " + response.status);
        const data = await response.json();
        console.log("fetch:", data);
        document.getElementById("out").textContent = data.user + " has " + data.points + " points";
      } catch (err) {
        console.log("fetch failed:", err.message);
      }
    });
  </script>
</body>
</html>

Effects without jQuery

A slide/fade toggle can be a CSS class plus a transition, or the Web Animations API:

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    .panel { overflow: hidden; max-height: 0; opacity: 0; transition: max-height .3s, opacity .3s;
             background: #eef5fb; padding: 0 10px; width: 260px; }
    .panel.open { max-height: 120px; opacity: 1; }
  </style>
</head>
<body>
  <button id="t">Toggle (CSS transition)</button>
  <div class="panel" id="p"><p>Animated purely by CSS — JavaScript only toggles a class.</p></div>
  <button id="shake">Shake (Web Animations API)</button>

  <script>
    document.getElementById("t").addEventListener("click", () => {
      const open = document.getElementById("p").classList.toggle("open");
      console.log("open:", open);
    });
    document.getElementById("shake").addEventListener("click", (e) => {
      e.currentTarget.animate(
        [{ transform: "translateX(0)" }, { transform: "translateX(-6px)" },
         { transform: "translateX(6px)" }, { transform: "translateX(0)" }],
        { duration: 300, iterations: 2 });
    });
  </script>
</body>
</html>

So which should you use?

jQuery is a reasonable choice when… Vanilla JS (or a framework) is better when…
The project already uses it everywhere You start a new project
You rely on jQuery plugins (DataTables, Select2, jQuery UI) Bundle size and load time matter
You need very short code for many small DOM tweaks You build a large stateful UI — consider React, Vue, Svelte, etc.

Test yourself

What is the vanilla equivalent of $el.one("click", fn)?

  1. el.onclick = fn
  2. el.addEventListener("click", fn, { once: true })
  3. el.click(fn)
  4. el.addEventListener("click", fn, true)

How does fetch behave when the server answers 404?

  1. It rejects the promise
  2. It resolves; you must check response.ok
  3. It throws synchronously
  4. It retries automatically

Which DOM API replaces $el.closest(".card")?

  1. el.parent(".card")
  2. el.closest(".card")
  3. el.querySelector(".card")
  4. el.matches(".card")