Plain JavaScript versus jQuery
Even a task as simple as this can be
complicated without jQuery at our disposal. In plain JavaScript, we could add the highlight
class in this way:
window.onload = function() { var divs = document.getElementsByTagName('div'); for (var i = 0; i < divs.length; i++) { if (hasClass(divs[i], 'poem-stanza') && !hasClass(divs[i], 'highlight')) { divs[i].className += ' highlight'; } } function hasClass( elem, cls ) { var reClass = new RegExp(' ' + cls + ' '); return reClass.test(' ' + elem.className + ' '); } };
Listing 1.3
Despite its length, this solution does not handle many of the situations that jQuery takes care of for us in Listing 1.2, such as:
Properly respecting other
window.onload
event handlersActing as soon as the DOM is ready
Optimizing element retrieval and other tasks with modern DOM methods
We can see that our jQuery-driven code is easier to write, simpler to read, and faster to execute than its plain JavaScript equivalent.