View Full Version : Walking through all children in body?

05-18-2004, 03:18 AM

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
//loop through the child nodes

//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 it has children we call the function again.



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.


This is for IE atm.

05-18-2004, 04: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


05-18-2004, 11: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.