使用 getElementsByClassName 似乎获取了太多元素

Ron*_*Ron 1 html javascript

运行以下代码并按下按钮应该会记录到控制台窗口 2 个元素,即带有class="test1"、按钮和 的p元素。并且console.log(el.length)2。但控制台记录的内容是这样的:

[p#div1.test1, 
 button#btn.test1, 
 div1: p#div1.test1, 
 btn: button#btn.test1] 
Run Code Online (Sandbox Code Playgroud)

看起来4元素不是2

这里发生了什么?

<html>
<body>
<p class="test1" id="div1">test1</p>
<button id="btn" onclick="getElements()" class="test1">Get Element List</button>
<script>
function getElements()
{
    var txt = document.getElementById("div1").innerHTML;

    var el = document.getElementsByClassName(txt);
    if (el) {
        console.log(el); 
        console.log(el.length); 
    }
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

chr*_*con 5

这是因为它返回的是一个 HTML Collection,它类似于数组,但不是数组。如果您将代码更改为

var el = document.getElementsByClassName(txt);
if (el) {
    console.log(Array.from(el)); 
    console.log(el.length); 
}
Run Code Online (Sandbox Code Playgroud)

这会将集合转换为数组,您将看到真正的数组,仅包含 2 个项目。

[p#div1.test1, button#btn.test1]
0: p#div1.test1
1: button#btn.test1
length: 2
Run Code Online (Sandbox Code Playgroud)

HTML Collection 公开了两种方法

HTMLCollection.item()
HTMLCollection.namedItem()
Run Code Online (Sandbox Code Playgroud)

这就是为什么条目数量看起来是两倍,但事实并非如此。