Stop using jQuery

Step outside your comfort zone! It takes more effort to include jQuery than it does to learn these simple native DOM methods.

Finding a single DOM node

First we take a look at how to natively find a element in a page. jQuery was great for quickly finding DOM nodes and getting a reference to that specific DOM element, but why add the extra kb (jQuery 3.2.1 is 86kb at the time of this writing) of a library when you can achieve the same thing natively and with even less code?

Somewhere in the page


w/jQuery


const $el = jQuery('.my-element');
const element = $el.get(0);

// Logs the height of the element
console.log(el.getBoundingClientRect().height);

Vanilla


const element = document.querySelector('.my-element');

// Logs the height of the element
console.log(el.getBoundingClientRect().height);

You can easily see why the native method is so much more straighforward and more intuitive because it returns the element itself instead of an object wrapper around the element that contains a whole instance of jQuery. This is great for one element but most times I need ALL of the elements on a page and a way to loop over each element, on to example #2!

Finding all selector matching DOM nodes

One of the conveniences of jQuery was a way to get all of the matching DOM nodes together and use methods such as .each() etc. For this example let's assume we have some media items in a grid on the page and we want to get all of the image URLs in an array.

Somewhere in the page


w/jQuery


const $imgs = jQuery('.media-item > img');
const imgURLs = [];

$imgs.each(function() {
  imgURLs.push($(this).attr('src'));
});

// Logs the image sources
console.log(imgURLs); // ["/item-1.jpg", "/item-2.jpg", etc.]

Vanilla


const mediaItems = [...document.querySelectorAll('.media-item > img')];
const imgURLs = mediaItems.map(
  element => element.querySelector('img').src
);

// Logs the image sources
console.log(imgURLs); // ["/item-1.jpg", "/item-2.jpg", etc.]

You can see from this example that with esentially two lines of code and 0 added kbs (we could have actually done it in one line...) that we can get all of the image elements and create an array of their URLs.