I wanted to traverse node by node on a web page by maintaining sequence.
e.g. Below is basic DOM :
<BODY>
<DIV id ='1'> Test 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
The jQuery traversing methods allow you to iterate DOM elements in a DOM hierarchy. Use the selector to get the reference of an element(s) and then call jQuery traversing methods to edit it. Important DOM manipulation methods: each(), children(), find(), first(), parent(), next(), previous(), siblings() etc.
What is Traversing? jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire. The image below illustrates an HTML page as a tree (DOM tree).
We can also traverse up the DOM tree, using the parentNode property. while (node = node. parentNode) DoSomething(node); This will traverse the DOM tree until it reaches the root element, when the parentNode property becomes null.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With