JavaScript中有集合,JavaScript中的HTMLCollection对象是类数组的HTML元素列表(集合)。getElementsByTagName()方法返回HTMLCollection对象。
JavaScript中的DOM集合:
length 属性定义了 HTMLCollection 中元素的数量:
示例:
JavaScript HTML DOM
Hello World!
Hello China!
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
"此文档包含 " + myCollection.length + " 段文字。";
运行结果:
实例解释:创建所有
元素的集合
显示集合的长度
注:
HTMLCollection 并非数组!
HTMLCollection 也许看起来像数组,但并非数组。
您能够遍历列表并通过数字引用元素(就像数组那样)。
不过,您无法对 HTMLCollection 使用数组方法,比如 valueOf()、pop()、push() 或 join()。