[thelist] Getting Child Elements from an HTML Element in JS

Gary McPherson genyus at ingenyus.net
Tue Jul 8 09:39:36 CDT 2003


> How do I retrieve the child elements of a HTML ELement using
>   Javascript? For example, I have this:
> 
> <div id ="topDiv">
>      <div id="parentDiv1">
> 	<div id="childDiv1">
> 	</div>
> 	<div id="childDiv2">
> 	</div>
>      </div>
> </div>
> 
> Given the element parentDiv1, how would I go about retrieving
> childDiv1 and childDiv2 programmatically?

Using the DOM, you would do something like this:

// get node list for parent node
objParent = document.getElementById("parentDiv1");
arrChildren = objParent.childNodes;

// loop thru all child nodes
for(i = 0; i < arrChildren.length; i++)
{
	objChild = arrChildren[i];
	// do something with node here
}

You might like to have a look at the W3C specs for further information:
http://www.w3c.org/DOM/

HTH,

Gary




More information about the thelist mailing list