When to Use Plain JS

Know when modern JavaScript can replace jQuery entirely.

Modern browsers now do natively much of what jQuery pioneered. For new projects, plain JavaScript is often enough.

jQueryModern JavaScript
$("#id")document.querySelector('#id')
$(".c")document.querySelectorAll('.c')
.on("click", fn).addEventListener('click', fn)
.addClass("x").classList.add('x')
$.getJSON(url)fetch(url).then(r => r.json())

jQuery still shines for maintaining existing code and quick prototypes. Choose the tool that fits the job.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A new React project skips jQuery entirely because JSX state management replaces all DOM manipulation jQuery was used for.
  • A Node.js script replaces $.ajax() with the native fetch() API since Node 18+ includes fetch without any library.
  • A developer migrating a legacy jQuery site replaces each .on('click') call with native addEventListener() as they refactor each component.

More examples

Replace $.ajax with fetch

fetch() is now built into all modern browsers and Node 18+, making $.ajax() unnecessary for new projects.

Example · html
// jQuery (old)
$.ajax({
  url: "/api/user",
  success: function (d) { console.log(d.name); }
});

// Vanilla JS (modern)
fetch("/api/user")
  .then(r => r.json())
  .then(d => console.log(d.name));

Replace .ready() with defer attribute

The defer attribute makes the script execute only after the DOM is parsed, fully replacing the need for $(document).ready().

Example · html
<!-- jQuery approach -->
<script src="app.js"></script> <!-- must use $(document).ready() -->

<!-- Modern vanilla approach -->
<script src="app.js" defer></script>
<!-- no ready() wrapper needed; DOM is guaranteed parsed -->

Replace $.each with native forEach/for...of

Array.prototype.forEach and for...of are native equivalents to $.each() and available in every modern environment.

Example · html
// jQuery
var items = ["a", "b", "c"];
$.each(items, function (i, v) { console.log(i, v); });

// Vanilla JS
const items2 = ["a", "b", "c"];
items2.forEach((v, i) => console.log(i, v));

// or
for (const v of items2) { console.log(v); }

Discussion

  • Be the first to comment on this lesson.