Home > Web Front-end > JS Tutorial > body text

javascript abnormal node collection_javascript skills

WBOY
Release: 2016-05-16 18:31:04
Original
980 people have browsed it

[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

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)
}


[Ctrl A Select all Note:
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也是这个样子,因此处理这类节点集合要打起十二分精神了!

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

这两种节点集合在各浏览器还实现得不太一样,如标准浏览器我们可以用Array.prototype.slice.call将它们转换为原生数组,IE则报错。标准浏览器的它们有hasOwnProperty与valueOf,而IE是没有的……
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template