主要不同在于HTMLCollection是元素集合而NodeList是節(jié)點集合(即可以包含元素弥虐,也可以包含文本節(jié)點)。
NodeList跟HTMLCollection有個差異是前者沒有namedItem()方法后者是有的。
NodeList的元素是Node,HTMLCollection的元素是Element,Element繼承自Node,是Node的一種穗酥,在HTML中,它一般是HTML元素(比如p,a之類的標(biāo)簽創(chuàng)建出來的對象)迷扇。而Node作為父類百揭,除了Element還有一些其他子類,比如HTML元素內(nèi)的文本對應(yīng)的Text蜓席,文檔對應(yīng)的Document,注釋對應(yīng)的Comment课锌。
HTMLCollection里厨内,只有Element,而NodeList里可以有Element渺贤、Text雏胃、Comment等多種元素。按說如果獲取元素返回的列表里只有Element志鞍,那這兩種類沒多大區(qū)別瞭亮,但事實上很多時候瀏覽器會將解析HTML文本時得到的Text和Comment一并放進(jìn)列表里放回。
所以 node.childNodes 返回NodeList固棚,而 node.children 和node.getElementsByXXX 返回 HTMLCollection 统翩,只有document.getElementsByName返回的還是NodeList對象,還有另一個比較特殊的是querySelectorAll 返回的雖然是 NodeList 此洲,但是實際上是元素集合厂汗,并且是靜態(tài)的(其他接口返回的HTMLCollection和NodeList都是live的)。
在chrome上node.getElementByTagName("")得到的是HTMLCollection[
]是live的呜师;而node.querySlectorAll("")得到的是NodeList[
]娶桦,注意: querySelectorAll 返回的雖然是NodeList ,但是實際上是元素集合汁汗,集合長度可以看出來(不包含空格text節(jié)點衷畦,不包含注釋節(jié)點),并且是靜態(tài)的(其他接口返回的HTMLCollection和NodeList都是live的)是static的
// 在chrome上
//使用querySelectorAll時知牌,移除子節(jié)點使用removeChild(childrens[i]);是static的有序集合
<div id ="div">
<p></p>
<p></p>
.......
<p></p>
<p></p>
</div>
<script>
**var**parent=**document**.querySelector(**"#div"**);
**var**childrens=parent.querySelectorAll(**"p"**);
**var**length=childrens.**length**;
alert(length);
**for**(**var**i=0;i<length;i++){
parent.removeChild(childrens[i]);
}
//使用getElementByTagName時祈争,移除子節(jié)點使用removeChild(childrens[0]);是live的有序集合
**var**parent=**document**.querySelector(**"#div"**);
**var**childrens=parent.getElementByTagName(**"p"**);
**var**length=childrens.**length**;
alert(length);
**for**(**var**i=0;i<length;i++){
parent.removeChild(childrens[0]);
}
</script>```