Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vanilla JS equivalents of jQuery methods

Sans jQuery

Events

// jQuery
$(document).ready(function() {
  // code
})

// Vanilla
document.addEventListener('DOMContentLoaded', function() {
  // code
})
// jQuery
$('a').click(function() {
  // code…
})

// Vanilla
[].forEach.call(document.querySelectorAll('a'), function(el) {
  el.addEventListener('click', function() {
    // code…
  })
})

Selectors

// jQuery
var divs = $('div')

// Vanilla
var divs = document.querySelectorAll('div')
// jQuery
var newDiv = $('<div/>')

// Vanilla
var newDiv = document.createElement('div')

Attributes

// jQuery
$('img').filter(':first').attr('alt', 'My image')

// Vanilla
document.querySelector('img').setAttribute('alt', 'My image')

Classes

// jQuery
newDiv.addClass('foo')

// Vanilla
newDiv.classList.add('foo')
// jQuery
newDiv.toggleClass('foo')

// Vanilla
newDiv.classList.toggle('foo')

Manipulation

// jQuery
$('body').append($('<p/>'))

// Vanilla
document.body.appendChild(document.createElement('p'))
// jQuery
var clonedElement = $('#about').clone()

// Vanilla
var clonedElement = document.getElementById('about').cloneNode(true)
// jQuery
$('#wrap').empty()

// Vanilla
var wrap = document.getElementById('wrap')
while(wrap.firstChild) wrap.removeChild(wrap.firstChild)

Transversing

// jQuery
var parent = $('#about').parent()

// Vanilla
var parent = document.getElementById('about').parentNode
// jQuery
if($('#wrap').is(':empty'))

// Vanilla
if(!document.getElementById('wrap').hasChildNodes())
// jQuery
var nextElement = $('#wrap').next()

// Vanilla
var nextElement = document.getElementById('wrap').nextSibling

AJAX

GET

// jQuery
$.get('//example.com', function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.open('GET', url)
httpRequest.send()

POST

// jQuery
$.post('//example.com', { username: username }, function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.open('POST', url)
httpRequest.send('username=' + encodeURIComponent(username))

JSONP

// jQuery
$.getJSON('//openexchangerates.org/latest.json?callback=?', function (data) {
  // code
})

// Vanilla
function success(data) {
  // code
}
var scr = document.createElement('script')
scr.src = '//openexchangerates.org/latest.json?callback=formatCurrency'
document.body.appendChild(scr)

More

Here are a few additional references demonstrating vanilla javascript equivalents of jquery methods:

Also, see the two part series showing equivalents for ...

@yairEO

This comment has been minimized.

Copy link

@yairEO yairEO commented Oct 14, 2016

$('#wrap').next() is not the same at all as vanilla nextSibling, but to nextElementSibling, because obviously nextSibling returns text nodes which are irrelevant.

Regarding the example of $('img').filter(':first').attr('alt', 'My image') - nobody in their right mind will use filter like that. you would simply do:

$('img:first')
$('img').eq(0)
$('img:eq(0)')

would be nice to add vanillia of wrap() method and data() method for storing data on a cached object

@brmendez

This comment has been minimized.

Copy link

@brmendez brmendez commented Apr 27, 2017

$('selector').load() would be nice 👍

@filipe-torres

This comment has been minimized.

Copy link

@filipe-torres filipe-torres commented May 31, 2017

@yairEO ,
I found a good JQuery wrap() method in plain Javascript: [(https://plainjs.com/javascript/manipulation/wrap-an-html-structure-around-an-element-28/)]

@brmendez ,
there is an alternative for JQuery load() method: loadPageSection.js
[(https://gist.github.com/lazamar/f213d94d08a8212bb0a59a4ec2fbc964)]

@dustinpoissant

This comment has been minimized.

Copy link

@dustinpoissant dustinpoissant commented Jun 20, 2017

I am rewriting one of my projects that has jQuery as a dependency to not have any dependencies. I was googling each line I needed to change until I found this. This is very useful, thank you.

@AaronKWalker

This comment has been minimized.

Copy link

@AaronKWalker AaronKWalker commented Jun 27, 2017

I'm currently learning javascript and jQuery. This helps out tremendously! Thank you!

@xilin

This comment has been minimized.

Copy link

@xilin xilin commented Jan 19, 2018

Base on jQuery's doc

By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, ). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.

These methods will execute code, while the vanilla method will not eval scripts.

@ameenaziz

This comment has been minimized.

Copy link

@ameenaziz ameenaziz commented Feb 1, 2018

$(btn[index++]).click();
whats evq for that?

@imlinus

This comment has been minimized.

Copy link

@imlinus imlinus commented Feb 19, 2018

document.querySelector(btn[index++]).click();

@daphnedeng

This comment has been minimized.

Copy link

@daphnedeng daphnedeng commented Jun 7, 2018

how about eq() ? What is eq() is vanilla js?

@grestart

This comment has been minimized.

Copy link

@grestart grestart commented Jun 27, 2018

what about this?

$( document ).ajaxComplete(function() {
// code here to change element, witch is loaded with ajax
});
@mtness

This comment has been minimized.

@mc-funk

This comment has been minimized.

Copy link

@mc-funk mc-funk commented Oct 5, 2018

Thanks for the great resource!

For the following:

// jQuery
$('#wrap').empty()

// Vanilla
var wrap = document.getElementById('wrap')
while(wrap.firstChild) wrap.removeChild(wrap.firstChild)
Why not wrap.innerHTML = '' or similar?
The while loop poses a problem if you are, e.g., ensuring that data refreshes probably -- since it will clear out anything you subsequently put into the element.

@aristot

This comment has been minimized.

Copy link

@aristot aristot commented Oct 7, 2018

while is faster than $().empty or wrap.innerHTML = ""

@MINORITYmaN

This comment has been minimized.

Copy link

@MINORITYmaN MINORITYmaN commented Nov 29, 2018

nobody cares about performance?
document.querySelectorAll('a') change to document.getElementsByTagName('a') why? first is browser API second i native.
you should check out this video btw.
https://youtu.be/VBfvnKDlZMw?t=597

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Jan 4, 2019

thank you
this is very useful :)

@yogyogi

This comment has been minimized.

Copy link

@yogyogi yogyogi commented Feb 19, 2019

I think jQuery Append method is perfect for all types of DOM manipulations. @brmendez $('selector').load() method is removed few years back, now there is .load() method for doing AJAX request only.

@darrellgrant

This comment has been minimized.

Copy link

@darrellgrant darrellgrant commented Mar 1, 2019

Thanks!

@graphical-iain

This comment has been minimized.

Copy link

@graphical-iain graphical-iain commented Apr 2, 2019

Fetch is also widely supported now. Fully supported with a relatively lightweight pollyfill for IE. So AJAX calls are just as easy with Vanilla JS now as with jQuery. :)

@trae410

This comment has been minimized.

Copy link

@trae410 trae410 commented Apr 30, 2019

I finally found a way to get the vanilla js equivalent of:

var item = $('form input');
var todo = {item: item.val()};

it is simple! here it is:

var item = document.querySelectorAll('input')[0];
var todo = {item: item.value)};

I was trying to use innerHTML, text etc, but is simply .value :)

@johnsfuller

This comment has been minimized.

Copy link

@johnsfuller johnsfuller commented Jul 1, 2019

love it! Maybe add a $(el).closest() equivalent?

@Asharif88

This comment has been minimized.

Copy link

@Asharif88 Asharif88 commented Jul 4, 2019

@jfudman

love it! Maybe add a $(el).closest() equivalent?

It's also .closest() https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

@ColdHandz

This comment has been minimized.

Copy link

@ColdHandz ColdHandz commented Jul 15, 2019

While this may be true, the browser support for many of those methods are somewhat different. Methods like classList.add may not be supported in older browsers.

Just take a moment to see how long and tedious polyfill for classList is.

@mzaini30

This comment has been minimized.

Copy link

@mzaini30 mzaini30 commented Mar 19, 2020

Fetch is also widely supported now. Fully supported with a relatively lightweight pollyfill for IE. So AJAX calls are just as easy with Vanilla JS now as with jQuery. :)

Yes....

@jsergiu

This comment has been minimized.

Copy link

@jsergiu jsergiu commented May 22, 2020

$('selector').load() would be nice 👍

`
// You can do something like:
< div class="include" data-file="./components/footer.html">

document.querySelectorAll('include').forEach((tag) => {
fetch(tag.dataset.file)
.then((r) => r.text())
.then((r) => $(tag).replaceWith($(r)))
})
`

@bigabdoul

This comment has been minimized.

Copy link

@bigabdoul bigabdoul commented Sep 14, 2020

$('#wrap').next() is not the same at all as vanilla nextSibling, but to nextElementSibling, because obviously nextSibling returns text nodes which are irrelevant.

Regarding the example of $('img').filter(':first').attr('alt', 'My image') - nobody in their right mind will use filter like that. you would simply do:

$('img:first')
$('img').eq(0)
$('img:eq(0)')

would be nice to add vanillia of wrap() method and data() method for storing data on a cached object

An implementation of jQuery's wrap() might be as follows:

In HTML:
<input type="text" id="textInput"/>

In jQuery:
$('#textInput').wrap('<div class="wrapped-input"></div>');

In JS:

/**
 * Creates a tag element, appends the specified child element to it and
 * then appends the created tag to the child's parent element.
 * @param {HTMLElement} child The child element to be contained in a new
 * wrapper element.
 * @param {string} Optional: The name of the tag element to create.
 * @returns HTMLElement The newly created tag element wrapped around child.
 */
function wrap(child, tag) {
    if (!tag) tag = "div";
    const parent = child.parentElement;
    const elm = document.createElement("" + tag); // ensures that 'tag' is really a string
    elm.appendChild(child);
    parent.appendChild(elm);
    return elm;
}

Usage:

wrap(document.getElementById('textInput')).setAttribute('class', 'wrapped-input');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.