Search code examples
javascriptdom

How can I loop through all DOM elements on a page?


I'm trying to loop over ALL elements on a page, so I want to check every element that exists on this page for a special class.

How do I check EVERY element?


Solution

  • You can pass a * to getElementsByTagName() so that it will return all elements in a page:

    var all = document.getElementsByTagName("*");
    
    for (var i=0, max=all.length; i < max; i++) {
         // Do something with the element here
    }
    

    Note that you could use querySelectorAll(), if it's available (IE9+, CSS in IE8), to just find elements with a particular class.

    if (document.querySelectorAll)
        var clsElements = document.querySelectorAll(".mySpeshalClass");
    else
        // loop through all elements instead
    

    This would certainly speed up matters for modern browsers.


    Browsers now support foreach on NodeList. This means you can directly loop the elements instead of writing your own for loop.

    document.querySelectorAll('*').forEach(function(node) {
        // Do whatever you want with the node object.
    });
    

    Performance note - Do your best to scope what you're looking for by using a specific selector. A universal selector can return lots of nodes depending on the complexity of the page. Also, consider using document.body.querySelectorAll instead of document.querySelectorAll when you don’t care about <head> children.