childNodes returns "undefined"

I am using childNodes in JavaScript to get the elements within a given element ID. It works just fine in IE, but not in Firefox, Chrome or Safari.

I alert the length of the childNodes array, it return 5 in IE, but the other browsers it returns 11. Although I have only 5 elements within the given Element ID. I am clueless on how to get this to work.

My code is below.


<td id="level2_options">
<div id="act_subcat" class="subcat">1</div>
<div id="res_subcat" class="subcat">2</div>
<div id="sleep_subcat" class="subcat">3</div>
<div id="trip_subcat" class="subcat">4</div>
<div id="trans_subcat" class="subcat">5</div>

JavaScript Code

var childs = document.getElementById('level2_options').childNodes;
		for(var i=0; i < childs.length; i++){

Thanks for any help.

The other browsers are including the newline characters. Use nodeName to identify the wanted elements.


What you should do to deal with the inconsistent behavior from IE, is to either get the elements explicitly, or if you’re walking through each child node, first check that you’re working with an actual element.

The first technique about getting the elements explicitly, uses the getElementsByTagName method:

var container = document.getElementById('level2_options');
var childs = container.getElementsByTagName('div');
for (var i = 0; i < childs.length; i += 1) {

The second technique checks the type of element that you’re working with.
Elements have a nodeType of 1, text nodes have a nodeType of 3:

childs = document.getElementById('level2_options').childNodes;
for (var i = 0; i < childs.length; i += 1) {
	if (childs.nodeType === 1) {