DOM traversal one by one node using jquery

I wanted to go through node to node in a web page, preserving the sequence.

eg. Below is the basic DOM:

<BODY> <DIV id ='1'> Test 1 </DIV> <DIV id='2'> Details about <SPAN id='3'> Execution </SPAN> </DIV> </BODY> 

As in the previous example, I want to go through node on node ie

 1st Traversal : <BODY> 2nd Traversal : <DIV id ='1'> 3rd Traversal : <DIV id='2'> 4rd Traversal : <SPAN id='3'> 

My motive is to loop over all the nodes available on the current page and visit each node one by one, saying just nextnode (), while the traversal does not apply to parent and child relationships. Exepcted, it must visit each node following the sequence.

So my statement will be like this:

 startnode //consider this is start node While ( startnode!=null ) { // will process on startnode startnode= startnode->nextnode(); // something like that to visit each node } 

Does anyone know how to do this using jquery (preferred) or javascript, please share your recommendations.

thanks

-Pravin

+4
source share
3 answers

There is always a standard Crockford method according to the dom method.

Example: http://jsfiddle.net/FJeaY/

 var walk_the_DOM = function walk(node, func) { func(node); node = node.firstChild; while (node) { walk(node, func); node = node.nextSibling; } }; walk_the_DOM(document.body, function(node) { if(node.nodeType == 1) alert(node.id); // alert if we have a type 1 node })​;​ 

A specific walk_the_DOM code walk_the_DOM , copied here: http://snipplr.com/view/19815/walking-the-dom/

EDIT: Text nodes have nodeType = 3 , so you can add this to your if() if they are desired.

 walk_the_DOM(document.body, function(node) { if(node.nodeType == 1 || node.nodeType == 3) alert(node.id); // ID will be undefined if it is a text node })​;​ 
+14
source

You can execute a loop with the body and the entire selector , for example:

 $("body").find("*").andSelf().each(function() { alert(this.nodeName); //alerts body, div, div, span });​ 

Note : andSelf deprecated and is now an alias for addBack() , which should be used with jQuery 1.8 and later

Here you can try here , the body part - this means that you are not getting <head> and this content, etc.

+11
source

Simple

 function walk(node, fn) { if (node) do { fn(node); if (node.nodeType === 1) walk(node.firstChild, fn); } while (node = node.nextSibling); } 

Using:

 walk(document.body, function(){ // do something with `this` // eg alert(this.id); }); 

And to avoid non-element nodes, this will work:

 function walk(node, fn) { if (node) do { if (node.nodeType === 1) { fn(node); walk(node.firstChild, fn); } } while (node = node.nextSibling); } 
+1
source

All Articles