JavaScript HTML DOM 集合(Collection)

Javascript 教程 · 2019-03-03 05:56:31

本章节介绍如何向文档中添加和移除元素(节点)。

HTMLCollection 对象

getElementsByTagName() 方法返回 HTMLCollection 对象。

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

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

实例

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

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

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

y = x[1];

HTMLCollection 对象 length 属性

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

实例

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

实例解析

获取 <p> 元素的集合:

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

显示集合元素个数:

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

集合 length 属性常用于遍历集合中的元素。

实例

修改所有 <p> 元素的背景颜色:

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

注意

HTMLCollection 不是一个数组!

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

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

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

点击查看所有 Javascript 教程 文章: https://codercto.com/courses/l/27.html

查看所有标签

BSD Hacks

BSD Hacks

Dru Lavigne / O'Reilly Media, Inc. / 2004-05-24 / USD 24.95

If you want more than your average BSD user--you want to explore and experiment, unearth shortcuts, create useful tools, and come up with fun things to try on your own--BSD Hacks is a must-have. This ......一起来看看 《BSD Hacks》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具