090_HTMLCollection和NodeList对象
1. HTMLCollection對象
1.1. HTMLCollection對象是類數組的html元素集合。
1.2. getElementsByTagName()和getElementsByClassName()方法返回HTMLCollection對象。
1.3. length屬性定義了HTMLCollection中元素的數量。
1.4. 可以通過名稱、id 或索引號訪問HTMLCollection。
2. NodeList對象
2.1. NodeList對象是從文檔中提取的節點列表。
2.2. querySelectorAll()方法和childNodes屬性返回NodeList對象。
2.3. length屬性定義了NodeList中元素的節點數。
2.4. 只能通過索引號訪問NodeList。
3. HTMLCollection與NodeList的區別
3.1. HTMLCollection對象是類數組的html元素集合。
3.2. NodeList對象是從文檔中提取的節點列表。
3.3. HTMLCollection和NodeList對象看起來像數組, 但并非數組。
3.4. HTMLCollection和NodeList對象無法使用數組的valueOf()、pop()、push()或join()等方法。
3.5. 可以通過名稱、id 或索引號訪問HTMLCollection。
3.6. 只能通過索引號訪問NodeList。
3.7. 只有NodeList對象能包含屬性節點和文本節點。
4. 例子
4.1. 代碼
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>HTMLCollection和NodeList對象</title></head><body><div id="div1"><p class="p">第一個p節點</p><p class="p">第二個p節點</p><p class="p">第三個p節點</p><span id="spanId" name="spanName" class="p">第一個span節點</span></div><script type="text/javascript">var ps = document.getElementsByTagName('p');document.write(ps + ', 集合的大小: ' + ps.length + '<br />');var classps = document.getElementsByClassName('p');document.write(classps + ', 集合的大小: ' + classps.length + '<br />');var qsaP = document.querySelectorAll(".p");document.write(qsaP + ', 列表的長度: ' + qsaP.length + '<br />');var div1ChildNodes = document.getElementById('div1').childNodes;document.write(div1ChildNodes + ', 列表的長度: ' + div1ChildNodes.length + '<br />');document.write('HTMLCollection可以通過id來訪問: ' + classps['spanId'] + '<br />');document.write('HTMLCollection可以通過name來訪問: ' + classps['spanName'] + '<br />');document.write('HTMLCollection可以通過索引號來訪問: ' + classps[classps.length - 1] + '<br />');document.write('NodeList不能通過id來訪問: ' + div1ChildNodes['spanId'] + '<br />');document.write('NodeList不能通過name來訪問: ' + div1ChildNodes['spanName'] + '<br />');document.write('NodeList只能通過索引號來訪問: ' + div1ChildNodes[div1ChildNodes.length - 2] + '<br />');</script></body> </html>4.2. 效果圖
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的090_HTMLCollection和NodeList对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 089_DOM节点动态创建、添加和删除
- 下一篇: 015_获取并设置CSS类