How do I convert old jQuery code to plain JavaScript?
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.
Cite
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.- Teodora VanceStaffModerator: HTML, CSS and front end JavaScript ·
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.
// 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:
// 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 theDOMContentLoadedevent ondocument. If your script tag sits at the end of the body, or uses thedeferattribute, you can often skip the wrapper entirely.$('#save')finds elements with a CSS selector. querySelector() takes the same kind of selector string and returns the first matching element, ornullif nothing matches. Thatnullis 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?.The second jQuery call is a delegated handler. The jQuery .on() documentation 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')one.targetto find which list item was clicked. Thetasks.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:
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 checkresponse.ok, as above.Mistakes to watch for
- 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, usequerySelectorAll('.card').forEach((card) => card.classList.add('x')). We compare the two methods in querySelector or querySelectorAll: which one should I use?. - Using
$(this)out of habit. Inside an arrow function,thisis not the clicked element. Use theeargument:e.currentTargetis the element the listener is on, ande.targetis what was actually clicked. - 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
- Search your files for
$(andjQuery(and list what is used. Many sites only use five or six methods. - Convert the page ready wrapper and the event handlers first.
- Convert one feature, open the browser console, and click through it.
- Convert Ajax calls last, and test the failure case by pointing the URL at a wrong path.
- 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 shows what the original code was doing.
- Expecting one element to behave like a jQuery set.
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.