手册
目录
getElementsByTagName() 方法返回 HTMLCollection 对象。
HTMLCollection 对象是类数组的 HTML 元素列表(集合)。
下面的代码选取文档中的所有
元素:
var x = document.getElementsByTagName("p");
该集合中的元素可通过索引号进行访问。
如需访问第二个
元素,您可以这样写:
y = x[1];运行实例 »
点击 "运行实例" 按钮查看在线实例
注释:索引从 0 开始。
length 属性定义了 HTMLCollection 中元素的数量:
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myCollection.length;
运行实例 »点击 "运行实例" 按钮查看在线实例
元素的集合
length 属性在您需要遍历集合中元素时是有用的:
改变所有
元素的背景色:
var myCollection = document.getElementsByTagName("p");
var i;
for (i = 0; i < myCollection.length; i++) {
myCollection[i].style.backgroundColor = "red";
}
运行实例 »点击 "运行实例" 按钮查看在线实例
HTMLCollection 也许看起来像数组,但并非数组。
您能够遍历列表并通过数字引用元素(就像数组那样)。
不过,您无法对 HTMLCollection 使用数组方法,比如 valueOf()、pop()、push() 或 join()。
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.2万人学习
共49课时
77万人学习
共29课时
61.7万人学习
共25课时
39.3万人学习
共43课时
70.9万人学习
共25课时
61.6万人学习
共22课时
23万人学习
共28课时
33.9万人学习
共89课时
125万人学习