getElementsByTagName()
方法返回一个 HTMLCollection
对象。
HTMLCollection
对象是 HTML 元素的类似数组的列表(集合)。
以下代码选择文档中的所有 <p>
元素:
const myCollection = document.getElementsByTagName("p");
集合中的元素可以通过索引号来访问。
要访问 您可以编写第二个 <p> 元素:
myCollection[1]
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
const myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = "The innerHTML of the second paragraph is: " + myCollection[1].innerHTML;
</script>
</body>
</html>
注意:索引从0开始。
length
属性定义 HTMLCollection
中的元素数量:
myCollection.length
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
const myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = "This document contains " + myCollection.length + " paragraphs.";
</script>
</body>
</html>
当您想要循环遍历 a 中的元素时,length
属性非常有用。 收藏:
更改所有 <p> 元素的文本颜色:
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p>Click the button to change the color of all p elements.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
}
</script>
</body>
</html>
HTMLCollection 不是数组!
HTMLCollection 可能看起来 就像一个数组,但它不是。
您可以循环浏览该列表并参考 带有数字的元素(就像数组一样)。
但是,您不能使用 valueOf()、pop()、push() 等数组方法, 或 HTMLCollection 上的 join()。