Comparing Scripts in jQuery and JavaScript: A Comparison by Jeffrey Way

In a recent post, From jQuery to JavaScript: A Reference, Jeffrey Way gives an excellent run-down of how to get scripty things done in three idioms: jQuery, current JavaScript, and legacy JavaScript.

It’s an outstanding read.

Item number one gives a great introduction to JavaScript’s new Selectors API, which approximates jQuery for its ability to query the DOM in CSS-selector style.

So for instance, compare these three ways of doing things:

Selecting Elements

jQuery

$('#container');

JavaScript

var container = document.querySelector('#container');

Legacy JavaScript

var container = document.getElementById('container');

Or consider this:

Add, Remove, and Toggle Classes

jQuery

$('#box').addClass('wrap');
$('#box').removeClass('wrap');
$('#box').toggleClass('wrap');

JavaScript

var container = document.querySelector('#box');
container.classList.add('wrap');
container.classList.remove('wrap');
container.classList.toggle('wrap');

Legacy JavaScript

var box = document.getElementById('box'),
 
    hasClass = function (el, cl) {
        var regex = new RegExp('(?:s|^)' + cl + '(?:s|$)');
        return !!el.className.match(regex);
    },
 
    addClass = function (el, cl) {
        el.className += ' ' + cl;
    },
 
    removeClass = function (el, cl) {
        var regex = new RegExp('(?:s|^)' + cl + '(?:s|$)');
        el.className = el.className.replace(regex, ' ');
    },
 
    toggleClass = function (el, cl) {
        hasClass(el, cl) ? removeClass(el, cl) : addClass(el, cl);
 
    };
 
addClass(box, 'drago');
removeClass(box, 'drago');
toggleClass(box, 'drago'); // if the element does not have a class of 'drago', add one.

Credit: These examples are from the post, From jQuery to JavaScript: A Reference, by Jeffrey Way.

Which is better? — or Which is better When?

As Way points out, the question is not necessarily “Which is better?” but “Which is better when?” JavaScript’s new Selector API goes a long way toward making vanilla JavaScript nearly as easy to work with as jQuery. In cases where we can get things done without loading the jQuery library, our sites will travel lighter and perform a bit snappier.

They take-away: The jQuery library is fantastic when you need it, but in each case, we should pause to ask: “Do I really need jQuery in this case? — Or can I get it done in straight JavaScript?”

Links