tags:

views:

1838

answers:

3

I need to access the DOM tree and get the elements just 1 level below the current element.

Read the following code:

<div id="node">
    <div id="a">
     <div id="aa">
      <div id="ab">
       <div id="aba"></div>
      </div>
     </div>
    </div>
    <div id="b">
     <div id="ba">
      <div id="bb">
       <div id="bba"></div>
      </div>
     </div>
    </div>
    <div id="c">
     <div id="ca">
      <div id="cb">
       <div id="cba"></div>
      </div>
     </div>
    </div>
</div>

I want to get the 3 elements "a", "b", "c" under "node". What should I do?

var nodes = node.getElementsByTagName("div") <---- I get all the divs but not the 3 divs I need.

var nodes = node.childNodes; <---- works in IE, but FF contains Text Node

Does anyone know how to solve the problem?

+5  A: 

You could use a function that rules out all non-element nodes:

function getChildNodes(node) {
    var children = new Array();
    for(var child in node.childNodes) {
        if(child.nodeType == 1) {
            children.append(child);
        }
    }
    return children;
}
Turismo
+1  A: 

I'd highly recommend you look at JQuery. The task you're looking to do is straightforward in pure Javascript, but if you're doing any additional DOM traversal, JQuery is going to save you countless hours of frustration. Not only that but it works across all browsers and has a very good "document ready" method.

Your problem solved with JQuery looks like:

$(document).ready(function() {
    var children = $("#node").children();
});

It looks for any element with an id of "node" then returns its children. In this case, children is a JQuery collection that can be iterated over using a for loop. Additionally you could iterate over them using the each() command.

Soviut
A: 

I think node.childNodes is the right place to start. You could (to make it work with FF too), test the nodeName (and possibly nodeType) of all child nodes you get, to skip text nodes.

Also you might have a look at some javascript library like prototype, which provide a lot of useful functions.

Ridcully