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

JavascriptDom

Javascript Problem Overview


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.

So, how do I say that I want to check EVERY element?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Was looking for same. Well, not exactly. I only wanted to list all DOM Nodes.

var currentNode,
    ni = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);

while(currentNode = ni.nextNode()) {
    console.log(currentNode.nodeName);
}

To get elements with a specific class, we can use filter function.

var currentNode,
    ni = document.createNodeIterator(
                     document.documentElement, 
                     NodeFilter.SHOW_ELEMENT,
                     function(node){
                         return node.classList.contains('toggleable') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
                     }
         );

while(currentNode = ni.nextNode()) {
    console.log(currentNode.nodeName);
}

Found solution on MDN

Solution 3 - Javascript

As always the best solution is to use recursion:

loop(document);
function loop(node){
    // do some thing with the node here
	var nodes = node.childNodes;
	for (var i = 0; i <nodes.length; i++){
		if(!nodes[i]){
			continue;
		}
		
		if(nodes[i].childNodes.length > 0){
			loop(nodes[i]);
		}
	}
}

Unlike other suggestions, this solution does not require you to create an array for all the nodes, so its more light on the memory. More importantly, it finds more results. I am not sure what those results are, but when testing on chrome it finds about 50% more nodes compared to document.getElementsByTagName("*");

Solution 4 - Javascript

Here is another example on how you can loop through a document or an element:

function getNodeList(elem){
var l=new Array(elem),c=1,ret=new Array();
//This first loop will loop until the count var is stable//
for(var r=0;r<c;r++){
	//This loop will loop thru the child element list//
	for(var z=0;z<l[r].childNodes.length;z++){
				
		 //Push the element to the return array.
		ret.push(l[r].childNodes[z]);
		
		if(l[r].childNodes[z].childNodes[0]){
			l.push(l[r].childNodes[z]);c++;
		}//IF			
	}//FOR
}//FOR
return ret;
}

Solution 5 - Javascript

For those who are using Jquery

$("*").each(function(i,e){console.log(i+' '+e)});

Solution 6 - Javascript

from this link
javascript reference

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
function findhead1()
{
    var tag, tags;
    // or you can use var allElem=document.all; and loop on it
    tags = "The tags in the page are:"
    for(i = 0; i < document.all.length; i++)
    {
        tag = document.all(i).tagName;
        tags = tags + "\r" + tag;
    }
    document.write(tags);
}

//  -->
</script>
</head>
<body onload="findhead1()">
<h1>Heading One</h1>
</body>
</html>

UPDATE:EDIT

since my last answer i found better simpler solution

function search(tableEvent)
    {
        clearResults()

        document.getElementById('loading').style.display = 'block';

        var params = 'formAction=SearchStocks';

        var elemArray = document.mainForm.elements;
        for (var i = 0; i < elemArray.length;i++)
        {
            var element = elemArray[i];

            var elementName= element.name;
            if(elementName=='formAction')
                continue;
            params += '&' + elementName+'='+ encodeURIComponent(element.value);

        }

        params += '&tableEvent=' + tableEvent;


        createXmlHttpObject();

        sendRequestPost(http_request,'Controller',false,params);

        prepareUpdateTableContents();//function js to handle the response out of scope for this question

    }

Solution 7 - Javascript

Andy E. gave a good answer.

I would add, if you feel to select all the childs in some special selector (this need happened to me recently), you can apply the method "getElementsByTagName()" on any DOM object you want.

For an example, I needed to just parse "visual" part of the web page, so I just made this

var visualDomElts = document.body.getElementsByTagName('*');

This will never take in consideration the head part.

Solution 8 - Javascript

Getting all elements using var all = document.getElementsByTagName("*"); for (var i=0, max=all.length; i < max; i++); is ok if you need to check every element but will result in checking or looping repeating elements or text.

Below is a recursion implementation that checks or loop each element of all DOM elements only once and append:

(Credits to @George Reith for his recursion answer here: https://stackoverflow.com/questions/12980648/map-html-to-json)

function mapDOMCheck(html_string, json) {
  treeObject = {}

  dom = new jsdom.JSDOM(html_string) // use jsdom because DOMParser does not provide client-side Window for element access
  document = dom.window.document
  element = document.querySelector('html')

  // Recurse and loop through DOM elements only once
  function treeHTML(element, object) {
    var nodeList = element.childNodes;

    if (nodeList != null) {
      if (nodeList.length) {
        object[element.nodeName] = []; // IMPT: empty [] array for parent node to push non-text recursivable elements (see below)

        for (var i = 0; i < nodeList.length; i++) {
          console.log("nodeName", nodeList[i].nodeName);

          if (nodeList[i].nodeType == 3) { // if child node is **final base-case** text node
            console.log("nodeValue", nodeList[i].nodeValue);
          } else { // else
            object[element.nodeName].push({}); // push {} into empty [] array where {} for recursivable elements
            treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length - 1]);
          }
        }
      }
    }
  }

  treeHTML(element, treeObject);

}

Solution 9 - Javascript

Use *

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

Solution 10 - Javascript

i think this is really quick

document.querySelectorAll('body,body *').forEach(function(e) {

Solution 11 - Javascript

You can try with document.getElementsByClassName('special_class');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlorian M&#252;llerView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascripttraditionalView Answer on Stackoverflow
Solution 3 - JavascriptIlya GazmanView Answer on Stackoverflow
Solution 4 - JavascriptJuggernogger93View Answer on Stackoverflow
Solution 5 - JavascriptMatas VaitkeviciusView Answer on Stackoverflow
Solution 6 - JavascriptshareefView Answer on Stackoverflow
Solution 7 - JavascriptkorvusView Answer on Stackoverflow
Solution 8 - JavascriptYi Xiang ChongView Answer on Stackoverflow
Solution 9 - Javascriptjacky wongView Answer on Stackoverflow
Solution 10 - Javascriptdefend orcaView Answer on Stackoverflow
Solution 11 - JavascriptJimish GamitView Answer on Stackoverflow