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

Hassan Schroeder hassan at webtuitive.com
Tue Jul 8 09:52:00 CDT 2003


Chris Evans wrote:

> How do I retrieve the child elements of a HTML ELement using Javascript? 

> <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?

Here's one approach; the 'thisChild.nodeType' line is to ignore
attribute (type 2) and text (type 3) nodes.

<script type="text/javascript">
                    /* Tested in Moz 1.4 and Opera 7.11 (Win) */
function init()
{
	var parent1 = document.getElementById("parentDiv1");
	var thisChild = parent1.firstChild;
	while ( thisChild != parent1.lastChild )
	{
		if ( thisChild.nodeType == 1 )
		{
			alert(thisChild.id);
		}
		thisChild = thisChild.nextSibling;
	}
}

window.onload=init;
</script>

HTH!
-- 
Hassan Schroeder ----------------------------- hassan at webtuitive.com
Webtuitive Design ===  (+1) 408-938-0567   === http://webtuitive.com

                           dream.  code.





More information about the thelist mailing list