JavaScript DOM 集合(Collection)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31561851/article/details/89006791

HTMLCollection 对象

getElementsByTagName() 方法返回 HTMLCollection 对象。

HTMLCollection 对象类似包含 HTML 元素的一个数组。

以下代码获取文档所有的 <p> 元素:

let x = document.getElementsByTagName("p");

集合中的元素可以通过索引(以 0 为起始位置)来访问。

访问第二个 <p> 元素可以是以下代码:

let y = x[1];

HTMLCollection 对象 length 属性

HTMLCollection 对象的 length 属性定义了集合中元素的数量。

let myCollection = document.getElementsByTagName("p");

document.getElementById("demo").innerHTML = myCollection.length;

集合 length 属性常用于遍历集合中的元素,修改所有

元素的背景颜色:

let myCollection = document.getElementsByTagName("p");

for (let i = 0; i < myCollection.length; i++) {
    myCollection[i].style.backgroundColor = "red";
}

注意:

  1. HTMLCollection 不是一个数组!

  2. HTMLCollection 看起来可能是一个数组,但其实不是。

  3. 你可以像数组一样,使用索引来获取元素。

  4. HTMLCollection 无法使用数组的方法: valueOf(), pop(), push(), 或 join() 。

猜你喜欢

转载自blog.csdn.net/qq_31561851/article/details/89006791