Are there vanilla alternatives to jQuery?

June 30, 2017

jQuery definitely has its shining moments. After all, there must be a reason for its enormous popularity. However, there are also many situations where the use of jQuery adds HTTP requests and data to transfer without enough justifying benefits.

The most useful feature of jQuery is DOM element selection:

let file_entries = $('.file-entry');

The vanilla way to do this is:

let file_entries = document.querySelectorAll('.file-entry');

which is much more verbose. However, we can write a simple function to shorten this syntax:

function $(x) {
  let y = Array.prototype.slice.call(document.querySelectorAll(x));
  if (y.length > 1) {
    return y;
  }
  else {
    return y[0];
  }
}

which returns either an array of DOM elements, or a single element if only one exists. This function lets us use jQuery’s convenient syntax to select DOM elements, all without the extra HTTP request and 32kB of data that jQuery comes with, and only at the cost of ~150 bytes of data.

What about class and html manipulations, or adding event listeners? There are vanilla ways to do those, as well. First, the jQuery way:

$('.slogan').addClass('red bold');
$('.slogan').html('Remember Reach');
$('.submit').on('click', myFunction);

Now the vanilla way (along with the function from above):

$('.slogan').classList.add('red','bold');
$('.slogan').innerHTML('Remember Reach');
$('.submit').addEventListener('click', myFunction);

For these particular utilizations, the vanilla method costs ~25 bytes more than the jQuery way, but again, saves on jQuery’s extra HTTP request and 32kB of data.

For most internet users in developed areas, the difference between loading 150 bytes and 32kB is too small for human perception, and attention spent on the difference can be seen as over-aggressive optimization. However, for many internet users not living in developed areas (think transfer speeds on the order of 1kB/sec), the difference in loading time can be over thirty seconds (see Chris Zacharias’ blog post for more on this issue).

There are times and places for jQuery. Just make sure that your project is one of them, before you use it.

For more info on vanilla alternatives to jQuery, check out youmightnotneedjquery.com

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive