1

I have a number of divs that I want to manipulate with events, like add/remove classes, attributes etc. I have nested elements. At first I was using the children collection, but since that was poorly supported I turned to childNodes.

However, now that I test it, with an alert to check the number of childNodes, I get e.g. 39 in all other browsers, and 20 in IE8. This makes looping unreliable, which I need to check for classes. My Javascript:

function removeOnclick(){
    var parent = document.getElementById('selections');
    var parent_length = parent.childNodes.length;
    alert(parent_length);
    for (var i=0; i<39; i+=2){
    if (parent.childNodes[i].hasAttribute("onclick")) {
        parent.childNodes[i].removeAttribute("onclick");
        }
    }
}

With this HTML formatting, all browsers count them as 20 (I have not pasted all 20 nodes):

<div id="selections"><div id="selection1" class="size" onclick="count(this.id);" onmouseover="onovershowpop(this.id);" onmouseout="onouthidepop(this.id);"><div class="pop">sample</div></div></div>

But with this formatting, all others browsers count 39 childNodes, while IE8 still counts 20:

<div id="selections">  
    <div id="selection1" class="size" onclick="count(this.id);" onmouseover="onovershowpop(this.id);" onmouseout="onouthidepop(this.id);">
        <div class="pop">sample</div>
    </div>
</div>

Do I have to go into one line (div tag) every time to make it bulletproof?

4

1 回答 1

3

IE8 及以下不将空文本节点计为子节点。.children[]从 5.5 甚至更早的版本开始,IE 就支持该数组,但该数组计算 IE8 及更低版本中的注释节点时存在轻微错误。只要元素中没有注释(不应该有,永远不需要 HTML 注释),那么您就可以.children[]可靠地使用。

于 2013-05-23T12:43:25.067 回答