TExcelTAD
Home › jQuery › Migrating away from jQuery

Migrating away from jQuery

Many teams decide to remove jQuery from a project — to cut ~30 KB of JavaScript, to drop an old dependency, or because they are moving to a framework. A good migration is gradual: you replace jQuery piece by piece while the site keeps working. This lesson gives you a practical plan and the code patterns you will need.

Step 1: Upgrade before you remove

If the project uses an old jQuery (1.x or 2.x), first upgrade to 3.7 with the official jQuery Migrate plugin. It restores removed APIs and prints a warning in the console every time old code uses one, which gives you a list of problems to fix.

html
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- development only: logs "JQMIGRATE: ..." warnings for deprecated usage -->
<script src="https://code.jquery.com/jquery-migrate-3.5.2.js"></script>

Common warnings and their fixes:

Old code Replace with
.bind(), .unbind(), .delegate(), .live() .on() / .off()
.click(fn), .hover(a, b) shorthands .on("click", fn), .on("mouseenter", a).on("mouseleave", b)
$(document).on("ready", fn) $(fn)
.size() .length
$.parseJSON(s) JSON.parse(s)
.success() / .error() / .complete() on jqXHR .done() / .fail() / .always()
$.isArray, $.trim, $.now, $.type Array.isArray, s.trim(), Date.now(), typeof

Step 2: Find out how jQuery is used

Search the code base to see which features you depend on. A quick inventory tells you where the work is:

bash
grep -rhoE "\.(on|ajax|getJSON|animate|fadeIn|fadeOut|slideToggle|addClass|each|data)\(" src/ | sort | uniq -c | sort -rn

Also list jQuery plugins (DataTables, Select2, jQuery UI). These usually decide your timeline, because each needs a non-jQuery replacement.

Step 3: Replace one module at a time

Pick a small, self-contained feature, rewrite it in vanilla JavaScript, and test it. Both styles can live on the same page during the transition — they operate on the same DOM.

Here is a typical jQuery component and its migrated version, both running together:

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 13px; }
    .faq { width: 300px; margin-bottom: 10px; }
    .faq h4 { margin: 0; padding: 6px 8px; background: #e3e9ef; cursor: pointer; border-top: 1px solid #fff; }
    .faq .a { padding: 6px 8px; background: #fafafa; }
    .faq .a[hidden] { display: none; }
    small { color: #888; }
  </style>
</head>
<body>
  <small>Before (jQuery)</small>
  <div class="faq" id="old">
    <h4>Shipping?</h4><div class="a" hidden>2–4 working days.</div>
    <h4>Returns?</h4><div class="a" hidden>Free within 30 days.</div>
  </div>
  <small>After (vanilla)</small>
  <div class="faq" id="new">
    <h4>Shipping?</h4><div class="a" hidden>2–4 working days.</div>
    <h4>Returns?</h4><div class="a" hidden>Free within 30 days.</div>
  </div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    // BEFORE: jQuery
    $("#old").on("click", "h4", function () {
      const $answer = $(this).next(".a");
      $("#old .a").not($answer).prop("hidden", true);
      $answer.prop("hidden", !$answer.prop("hidden"));
      console.log("jQuery FAQ:", $(this).text());
    });

    // AFTER: vanilla JavaScript, same behaviour
    const faq = document.getElementById("new");
    faq.addEventListener("click", (e) => {
      const q = e.target.closest("h4");
      if (!q || !faq.contains(q)) return;
      const answer = q.nextElementSibling;
      faq.querySelectorAll(".a").forEach(a => { if (a !== answer) a.hidden = true; });
      answer.hidden = !answer.hidden;
      console.log("vanilla FAQ:", q.textContent);
    });
  </script>
</body>
</html>

Step 4: Small helpers instead of a big library

If many files use $ for quick lookups, a few tiny helpers make the vanilla code nearly as short — and are easy to delete later:

html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
  <ul id="list"><li>one</li><li>two</li><li>three</li></ul>
  <button id="mark">Mark all</button>

  <script>
    // ~10 lines that cover the most common jQuery uses
    const $ = (sel, root = document) => root.querySelector(sel);
    const $ = (sel, root = document) => [...root.querySelectorAll(sel)];
    const on = (el, type, selOrFn, fn) => {
      if (typeof selOrFn === "function") return el.addEventListener(type, selOrFn);
      el.addEventListener(type, e => {
        const match = e.target.closest(selOrFn);
        if (match && el.contains(match)) fn.call(match, e);
      });
    };

    on($("#mark"), "click", () => {
      $("#list li").forEach(li => li.style.fontWeight = "bold");
      console.log("marked", $("#list li").length, "items");
    });
    on($("#list"), "click", "li", function () {
      this.style.color = "crimson";              // delegated, `this` = the li
      console.log("clicked", this.textContent);
    });
  </script>
</body>
</html>

Note: Do not name such helpers $ while jQuery is still loaded on the page — use qs/qsa or keep them inside modules. Otherwise you create exactly the conflict noConflict() exists for.

Step 5: Replace AJAX calls

Wrap fetch in one small function that behaves like jQuery (rejects on HTTP errors, parses JSON), then swap call sites one by one:

js
async function getJSON(url, params) {
  const query = params ? "?" + new URLSearchParams(params) : "";
  const res = await fetch(url + query, { headers: { Accept: "application/json" } });
  if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
  return res.json();
}

// before: $.getJSON("/api/users", { page: 2 }).done(render).fail(showError);
// after:
getJSON("/api/users", { page: 2 }).then(render, showError);

Step 6: Remove the script tag

When the search for $(, jQuery and .fn. comes back empty (and no plugin needs it), remove the <script> tag or npm uninstall jquery. Run your tests and click through the site with the browser console open.

Common pitfalls

Pitfall Why it bites
querySelector returns null jQuery silently ignores empty sets; vanilla code throws Cannot read properties of null. Check or use ?.
Forgetting loops .addClass() affected all matches; classList.add affects one element
dataset values are strings $el.data("count") returned a number; el.dataset.count is "5"
.hide()/.show() Replace with hidden, a class, or style.display — and check CSS that relied on inline display
Event handler this Arrow functions do not bind this; use e.currentTarget
fetch doesn't reject on 404 Check response.ok

Test yourself

What is jQuery Migrate used for?

  1. Converting jQuery code to React automatically
  2. Restoring removed APIs and logging warnings when old code uses them
  3. Moving files between servers
  4. Minifying jQuery

$("#missing").addClass("x") does nothing. What does document.querySelector("#missing").classList.add("x") do?

  1. Also nothing
  2. Throws a TypeError because querySelector returned null
  3. Creates the element
  4. Adds the class to body

What is the recommended migration strategy?

  1. Delete jQuery first, then fix whatever breaks
  2. Replace features gradually, module by module, while both coexist
  3. Rewrite the whole site in one release
  4. Keep jQuery but remove all plugins