Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
107
rated 0 times [  114] [ 7]  / answers: 1 / hits: 29476  / 16 Years ago, fri, february 27, 2009, 12:00:00

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?


More From » dom

 Answers
71

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;
}

[#99917] Friday, February 20, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;