Search code examples
javascriptgoogle-chromeundefinedgetelementsbytagname

Why is getElementsByTagName() returning an html collection, but getElementsByTagName()[0] returning undefined?


I am working on a chrome extension that uses content scripts. I am attempting to get an element of a page, but I am getting results I have never encountered. Here is the code I am running, once the page loads.

var iframe = document.getElementsByTagName("iframe");
console.log(iframe);
console.log(iframe[0]);

The first log returns an HTML Collection with a length of 1, and the first element is defined fully as an iframe element.

The second log returns undefined.

I must be missing something obvious, anyone know what is going on?

I have also attempted item(0), with negative results.

I have attempted getting IDs, classes, and other methods of reference DOM elements, they all work. But classes has the same issue here, it will return an array of elements, but if I attempt to reference the first element, it is always undefined.


Solution

  • Problem is it is a Live HTMLCollection. So it updates! You are referencing it before the element exists.

    <script>
      var iframe = document.getElementsByTagName("iframe");
      console.log("1", iframe);
      console.log("2", iframe[0]);
    </script>
    <iframe></iframe>
    <script>
      console.log("3", iframe);
      console.log("4", iframe[0]);
      iframe[0].remove();
      console.log("5", iframe);
      console.log("6", iframe[0]);
    </script>