# How do I convert old jQuery code to plain JavaScript?

Source: https://coursesweb.net/forum/t/how-do-i-convert-old-jquery-code-to-plain-javascript/
Site: CoursesWeb Forum, category jQuery and Older Front End Code
Published: 2026-11-15. Updated: 2026-11-15. Replies: 0.

## Question by Teodora Vance (staff), 2026-11-15

Convert it one habit at a time, not all at once. Replace $() with document.querySelector or querySelectorAll, .on() with addEventListener, .addClass() with classList.add, and $.ajax with fetch. Keep jQuery on the page until the last call is gone, and test after each small change so you know which edit broke something.

## The same page behaviour, before and after

Here is a typical old snippet. It saves on click, shows a message, and marks list items as done.

```js
// jQuery version
$(function () {
  $('#save').on('click', function (e) {
    e.preventDefault();
    $('.msg').text('Saved').addClass('ok');
  });

  $('#tasks').on('click', 'li', function () {
    $(this).toggleClass('done');
  });
});
```

And the plain JavaScript version that does the same work:

```js
// plain JavaScript version
document.addEventListener('DOMContentLoaded', () => {
  const save = document.querySelector('#save');
  const msg = document.querySelector('.msg');
  const tasks = document.querySelector('#tasks');

  save.addEventListener('click', (e) => {
    e.preventDefault();
    msg.textContent = 'Saved';
    msg.classList.add('ok');
  });

  tasks.addEventListener('click', (e) => {
    const li = e.target.closest('li');
    if (li && tasks.contains(li)) {
      li.classList.toggle('done');
    }
  });
});
```

## Why each piece maps over

`$(function () { ... })` waits until the page structure is ready. The plain equivalent is the `DOMContentLoaded` event on `document`. If your script tag sits at the end of the body, or uses the `defer` attribute, you can often skip the wrapper entirely.

`$('#save')` finds elements with a CSS selector. [querySelector()](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) takes the same kind of selector string and returns the first matching element, or `null` if nothing matches. That `null` is the root of many "cannot read properties of null" errors, which we explain in [Why does getElementById return null and break innerHTML in my script?](/forum/t/why-does-getelementbyid-return-null-and-break-innerhtml-in-my-script/).

The second jQuery call is a delegated handler. The [jQuery .on() documentation](https://api.jquery.com/on/) explains that when you pass a selector, the handler runs for descendants that match it, including ones added later. Plain JavaScript does the same with one listener on the parent, then `closest('li')` on `e.target` to find which list item was clicked. The `tasks.contains(li)` check stops a click from matching a list item outside your list.

## Common conversions

| jQuery | Plain JavaScript |
| --- | --- |
| `$('.card')` (all matches) | `document.querySelectorAll('.card')` |
| `.text('Hi')` | `el.textContent = 'Hi'` |
| `.html(str)` | `el.innerHTML = str` (only with trusted text) |
| `.addClass('a')` / `.removeClass('a')` | `el.classList.add('a')` / `el.classList.remove('a')` |
| `.attr('href')` | `el.getAttribute('href')` |
| `.val()` | `input.value` |
| `.hide()` | `el.hidden = true` |
| `$.getJSON(url, fn)` | `fetch(url).then((r) => r.json())` |

A fetch version of a JSON request looks like this:

```js
async function loadItems() {
  const response = await fetch('/api/items');
  if (!response.ok) {
    throw new Error('Request failed with status ' + response.status);
  }
  return response.json();
}
```

Unlike `$.getJSON`, fetch does not treat a 404 or 500 as an error by itself. You have to check `response.ok`, as above.

## Mistakes to watch for

1. **Expecting one element to behave like a jQuery set.** `$('.card').addClass('x')` touches every card. `document.querySelector('.card')` returns only the first one. For all of them, use `querySelectorAll('.card').forEach((card) => card.classList.add('x'))`. We compare the two methods in [querySelector or querySelectorAll: which one should I use?](/forum/t/queryselector-or-queryselectorall-which-one-should-i-use/).
2. **Using `$(this)` out of habit.** Inside an arrow function, `this` is not the clicked element. Use the `e` argument: `e.currentTarget` is the element the listener is on, and `e.target` is what was actually clicked.
3. **Converting plugins by hand.** If a slider or date picker depends on jQuery, leave that part alone until you pick a replacement. Mixing is fine while you migrate.

## Check this in order

1. Search your files for `$(` and `jQuery(` and list what is used. Many sites only use five or six methods.
2. Convert the page ready wrapper and the event handlers first.
3. Convert one feature, open the browser console, and click through it.
4. Convert Ajax calls last, and test the failure case by pointing the URL at a wrong path.
5. Remove the jQuery script tag only when the console shows no "$ is not defined" errors.

If you want a reference for the old calls while you work, the CoursesWeb page on [getting an attribute with jQuery](https://coursesweb.net/jquery/get-attribute-id-class-name-title-src-jquery) shows what the original code was doing.

---
Cite as: CoursesWeb Forum, "How do I convert old jQuery code to plain JavaScript?", https://coursesweb.net/forum/t/how-do-i-convert-old-jquery-code-to-plain-javascript/, accessed 2026-11-16.
