Inspecting a large number of nodes

Another pitfall to avoid is trying to inspect a large number of nodes at once. It is much better to narrow down the search to a specific subset of nodes and then use built-in methods to find the desired nodes. For example, if we know that the node we are looking for can be found inside a specific div element, then we could use the following code example:

function myJS(){    let subsetElements = document.getElementById("specific-div").getElementsByTagName("*");        for(let i = 0; i < subsetElements.length; i++) {        if(subsetElements[i].hasAttribute("someattribute")) {            // Do something with the node that was found...            break;        }    }}

Thus, this search will be much more efficient and return results much faster than if we ...

Get Mastering The Faster Web with PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.