Even a task as simple as this can be complicated without jQuery at our disposal. In plain JavaScript, we could add the highlight class this way:
window.onload = function() {
const divs = document.getElementsByTagName('div');
const hasClass = (elem, cls) =>
new RegExp(` ${cls} `).test(` ${elem.className} `);
for (let div of divs) {
if (hasClass(div, 'poem-stanza') && !hasClass(div, 'highlight')) {
div.className += ' highlight';
}
}
};
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 handlers
- Acting 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.