Javascript – Get elements just 1 level below the current element by javascript

domjavascript

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?

Best Solution

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(node.childNodes[child].nodeType == 1) {
            children.push(child);
        }
    }
    return children;
}