GetElementsByTagName ƒ item() { [native code] } - What is this?

793 views Asked by At

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?

2

There are 2 answers

0
Sebastian Kaczmarek On BEST ANSWER

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 the HTMLCollection has additional properties (methods): item() and namedItem() which apparently are enumerable and this is why for-in iterates over them.

To avoid that, you can use a standard for-loop:

var elem = document.getElementsByTagName('li');
for (var i = 0; i < elem.length; i++) {
    console.log(elem[i]);
}

You can read about properties descriptors (e.x. enumerable) here.

0
CherryDT On

Methods. elem is an HTMLCollection, not an array, it has those methods, and they are historically enumerable.

Don't use for in. for in iterates over all keys of an object.

You can use for of instead:

for (const item of elem) {
  console.log(item) 
}

...or convert it to an array using Array.from(elem), then you can use all the regular array functionalities with it.

You can also go the old-fashioned way and just iterate from 0 to < length:

for (let i = 0; i < elem.length; i++) {
  console.log(elem[i])
}