getElementsByTagName() 方法返回 HTMLCollection 对象。
HTMLCollection 对象是类数组的 HTML 元素列表(集合)。
下面的代码选取文档中的所有
元素:
var x = document.getElementsByTagName("p");
该集合中的元素可通过索引号进行访问。【从0开始索引】
DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML DOMh1>
<p>Hello World!p>
<p>Hello China!p>
<p id="demo">p>
<script>
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
"第二段的 innerHTML 是:" +
myCollection[1].innerHTML;
script>
body>
html>

length 属性定义了 HTMLCollection 中元素的数量:
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myCollection.length;

【解释】
元素的集合
length属性在需要遍历集合中元素时是有用的:
【举个栗子】
改变所有
元素的背景色:

HTMLCollection 也许看起来像数组,但并非数组。
能够遍历列表并通过数字引用元素(就像数组那样)。
不过,无法对 HTMLCollection 使用数组方法,比如 valueOf()、pop()、push() 或 join()。