Reputation: 33
Running the following code and pressing the button should log to the console window 2 elements, the elements with the class="test1"
, the button and the p
element. And console.log(el.length)
is 2
. BUT what logs to console is this:
[p#div1.test1,
button#btn.test1,
div1: p#div1.test1,
btn: button#btn.test1]
which looks like 4
elements not 2
.
What is happening here?
<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>
Upvotes: 1
Views: 520
Reputation: 4868
The trick is that getElementsByClassName
doesn't return an array, but an HTMLCollection
.
HTMLCollection
has the information directly as properties "by both name and index", so that is why it looks like it has 4 members.
Upvotes: 2
Reputation: 73221
This is because it's a HTML Collection that is returned, which is array like, but not an array. If you change your code to
var el = document.getElementsByClassName(txt);
if (el) {
console.log(Array.from(el));
console.log(el.length);
}
which will turn the collection into an array, you will see the real array, containing only 2 items.
[p#div1.test1, button#btn.test1]
0: p#div1.test1
1: button#btn.test1
length: 2
A HTML Collection exposes two methods
HTMLCollection.item()
HTMLCollection.namedItem()
That's why it seems like it were double the amount of entries, though it's not.
Upvotes: 5