tags:

views:

431

answers:

2

Hi everyone,

I have a treeview with drag and drop functionality. Upon completion of drag and drop I need to find the count of the child nodes of the new parent node. So for that I'm using the following lines

var childnodelength=elem.parentNode.parentNode.childNodes.length;

alert(childnodelength);

But I always get the same value of 4 irrespective of the no. of childs, with the above alert. I've also tried in the following way.

alert(elem.getElementsByTagName("A")[0].childNodes.length);

Above line always gives me 1 irrespective of the no. of childs. I am not sure if I am referring correctly in both the ways.

And hence I'm unable to find the no. of child nodes.

Please could someone help me with this?

Thanks

A: 

Perhaps the child node is a DIV or Table that wraps up the nodes you need to count?

Oded
+1  A: 

Keep in mind that childNodes only looks one level down, so the value will be the same so long as you have the same number of immediate children. Perhaps what you wanted was to count all the children all the way down the tree?

If you want all the child elements, you can use getElementsByTagName("*"). Note that the use of the "*" argument doesn't work in IE5.5, which could also pose trouble for more recent versions of IE when running in quirks mode.

Another good thing to know about childNodes.length is that it may return a different value in IE than other browsers because of different ways of counting text nodes . . . If you want to exclude text nodes and only count elements you can loop through the childNodes and check the value of nodeType (1 = ELEMENT_NODE, 2 = ATTRIBUTE_NODE, 3 = TEXT_NODE, etc.) You can also use children instead of childNodes if you only want element nodes, but in IE this incorrectly counts comment nodes, and in Firefox it wasn't supported until version 3.5.

Tim Goodman