...

View Full Version : Walking through all children in body?



iceboxqs
05-18-2004, 02:18 AM
Hello,

I am trying to move through all the children of the <body> tag. If there is a span or div I want to look at their children. If their children have children I want to look at them as well, etc, etc.

However I am having a problem with my counter somehow screwing up, as the value of i seems to change after I get about 3 elements deep.

Here is a quick dirty example of my code:


//Input is a node, like <body>
function findChildren(node)
{

//Check for control type node
if(node.nodeName.toLowerCase() == "span" || node.nodeName.toLowerCase() == "div")
{
//Check for childnodes in control type node
if(node.nodeChilds.length>0)
{
//loop through the child nodes
for(i=0;i<node.nodeChilds.length;i++)
{

//See if the current child node is a span or a div.
if(node.nodeChilds[i].nodeName.toLowerCase() == "span" || node.nodeChilds[i].nodeName.toLowerCase() == "div")
{

//Do some formatting or what not to the span or div tag here.

}

//Check to see if the child node has children in it.
if(node.childNodes[i].childNodes.length>0)
{
//If it has children we call the function again.
findChildren(node.childNodes[i]);
}


}
}
}


}


When I get to an item that is say 3 elements deep in the original node I end up hitting an endless loop.

Any tips/ideas?

I am still very new to DOM scripting, as you can most likely tell.

P.S.

This is for IE atm.

jkd
05-18-2004, 03:11 AM
Why not do something like:



function traverse(top) {
for (var i = 0; i < top.childNodes.length; i++) {
switch (top.childNodes[i].nodeName.toLowerCase()) {
case "div":
case "span":
alert(top.childNodes[i]); // do whatever with it if necessary
traverse(top.childNodes[i]);
break;
}
}
}

traverse(document.body);

iceboxqs
05-18-2004, 10:39 PM
With your help and another suggestion from a friend (dealing with the formatting that I was doing) I got it working.

Thank you much.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum