]
If you convert nodeList to There is no problem with arrays!
The code is as follows:
window.onload = function(){
var d = document.createDocumentFragment();
var div = document.getElementById("aaa");
var c = div.childNodes;
var arr = [];
for(var i= 0,n=c.length;iarr.push(c[i])
}
for(var i=0,n=arr.length;ialert(arr[i] " " i)
d.appendChild(arr[i])
}
div.parentNode.replaceChild(d,div)
}
If you need to introduce external Js, you need to refresh it to execute
]
Obviously nodeList is a little weird. has features that arrays do not have. From running box 2, we can see that when appendChild the node to the document fragment, it will actually be separated from the DOM tree. nodeList must track this change and dynamically change itself, and linear increment i cannot Corresponds to the index of the correct node! So we just get its firstChild every time.
Copy code
The code is as follows:
window.onload = function(){
var d = document.createDocumentFragment();
var div = document.getElementById("aaa");
var c = div.childNodes;
while(c.length) d.appendChild(c[0] )//Only take its first node each time until it is empty
div.parentNode.replaceChild(d,div)
}
[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]
顺便一提,由getElementsByTagName取得的HTMLCollection也是这个样子,因此处理这类节点集合要打起十二分精神了!
这两种节点集合在各浏览器还实现得不太一样,如标准浏览器我们可以用Array.prototype.slice.call将它们转换为原生数组,IE则报错。标准浏览器的它们有hasOwnProperty与valueOf,而IE是没有的……