Searching for nodes

When searching for nodes through the entire DOM, it best to use XPath to do so. Often, a for loop is used, as per the following example where h2, h3 and h4 elements are being searched for:

function myJS(){    let elements = document.getElementsByTagName("*");        for(let i = 0; i < elements.length; i++) {        if(elements[i].tagName.match("/^h[2-4]$/i")) {            // Do something with the node that was found        }    }}

Instead of using this for loop, an XPath iterator object could be used to obtain the same result, only much more efficiently:

function myJS(){    let allHeadings = document.evaluate("//h2|//h3|//h4", document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);    let singleheading;     while(singleheading = allHeadings.iterateNext()) { ...

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.