开发者

Problem in using javascript childNodes.length property with elem

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 fol开发者_Go百科lowing 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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜