Get Children

How would I get the first level children and not get the grandchildren as well

for instance

<div id="topLevel">

so, if I am starting from the div with the ID of "topLevel" how do I get the child div's one level down and not the grandchild div. I've tried getElementByTagName and this returns all three div's when I only want to get 2 of them.
LVL 18
Who is Participating?

Improve company productivity with a Business Account.Sign Up

Hube02Connect With a Mentor Author Commented:
I decided to limit nested divs. So each div can only contain one child div. This allows me to use the getElementsByTagName and then take the first one which is the immediate child.

Not the best solution and not quite what I was looking for, but it will work for the intended purpose.
try this
	Set objXML = Server.CreateObject("Microsoft.XMLDOM")
    sXMLFile = Server.MapPath("\") & "\xmldoc.xml"
	Set oNodes = objXML.selectNodes("//div/*")
    For Each oChild In oNodes
        Response.Write oChild.tagname & "<BR>"

Open in new window

Hube02Author Commented:
You've lost me.

What does VBScript have to do with getting elements in JavaScript.

The purpose of this is so that I can set style properties dynamically.
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

David S.Commented:
Use the childNodes collection, but remember to check if each node is an element node by checking if the node's nodeType property is set to 1 or not.
Hube02Author Commented:
Not one to sit around and wait, I tried childNodes last night. The problem with this is that if there is some other type of element in there that is returned as well.

For instance if you have:


Both the div and the span are returned as element type 1. It seems no matter which route I go, I'm getting more information than I want.

Is there any way to tell what type of element each of the childNodes really is? Is it a div, span, ul. Seems to me there should be some way to get only the first level children of a specific element type.
David S.Connect With a Mentor Commented:
> Is there any way to tell what type of element each of the childNodes really is?

Sure. Use the nodeName property. (It's best to use toLowerCase() on it before comparing it to a string.)
neeraj523Connect With a Mentor Commented:
here is a the sample script which will read only divs in the documents..
	var divs = document.getElementsByTagName( 'DIV' );
    for ( var i = 0; i < divs.length; i++ ) 

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.