Even a task as simple as this can be complicated without jQuery at our disposal. In plain JavaScript, we could add the highlightedclass as shown in the following code snippet:
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 ' ');
}
};
When we handle it ourselves, even such a simple task is not used It gets complicated when using jquery. With raw js, we can add the highlighted class using the following code snippet:
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 the following :
• Properly respecting other window.onloadevent handlers
• Acting as soon as the DOM is ready
• Optimizing element retrieval and other tasks with modern DOM methods
Although long, this solution is still It does not handle many of the things that jquery does for us in Listing 1.2, such as the following:
1. Handle other window.load events appropriately
2. Start taking action when the DOM structure is ready.
3. Use modern DOM methods to optimize element search and other tasks.
We can see that our jQuery-driven code is easier to write, simpler to read, and faster to execute than its plain JavaScript equivalent.
We can clearly see that our use of query The code is easier to write, simpler to read, and faster to run than native js code.