With the code below
<ul>
<li>Rice</li>
<li>Coffee</li>
<li>Beans</li>
</ul>
<script>
var elem = document.getElementsByTagName('li')
for (var i in elem) {
console.log(elem[i])
}
</script>
I see five results, as follows.
<li>Rice</li>
<li>Coffee</li>
<li>Beans</li>
ƒ item() { [native code] }
ƒ namedItem() { [native code] }
What in the world are the last two items?
for-in
loop iterates over all enumerable properties of an object. The.getElementsByTagName()
method returns an HTMLCollection which can be iterated over. The thing is that theHTMLCollection
has additional properties (methods):item()
andnamedItem()
which apparently are enumerable and this is whyfor-in
iterates over them.To avoid that, you can use a standard
for-loop
:You can read about properties descriptors (e.x. enumerable) here.