DOM traversal one by one node using jquery
I wanted to traverse node by node on a web page by maintaining sequence.
e.g. Below is basic DOM :
<BODY>
<DIV id ='1'> Te开发者_StackOverflowst 1 </DIV>
<DIV id='2'> Details about <SPAN id='3'> Execution </SPAN> </DIV>
</BODY>
As per above example I want traverse each node by node i.e.
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 current page and visit each node one by one saying simply nextnode(), while traversing not looking in to parent and child relations. Exepcted is, it should visit each node by following 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
}
Is any one knows about this, how to achieve this using jquery(preferably) or javascript, please share their references.
Thanks
-Pravin
There's always the standard Crockford walk 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
});
Specific walk_the_DOM
code example copied from here: http://snipplr.com/view/19815/walking-the-dom/
EDIT: Text nodes have nodeType = 3
, so you can add that to your if()
statement if those are desired as well.
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
});
You can loop through with a body and all selector, like this:
$("body").find("*").andSelf().each(function() {
alert(this.nodeName); //alerts body, div, div, span
});
Note: andSelf
has been deprecated and is now an alias for addBack()
, which should be used with jQuery 1.8 and later
You can give it a try here, the body
portion is so you don't get the <head>
and it's contents, etc.
Simple.
function walk(node, fn) {
if (node) do {
fn(node);
if (node.nodeType === 1) walk(node.firstChild, fn);
} while (node = node.nextSibling);
}
Usage:
walk(document.body, function(){
// do something with `this`
// e.g.
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);
}
精彩评论