getElementsByTagName().length returns zero

mobius picture mobius · Apr 30, 2011 · Viewed 22.8k times · Source

I am trying to do a simple thing such as:

var elements = document.getElementsByTagName("input");
console.log(elements);
console.log(elements.length);

The console.log(elements) shows the NodeList containing 28 input elements, but the elements.length is always 0.

I've also seen this getElementsByTagName("div").length returns zero for any webpage however I didn't understand what exactly is the reason for it happening and how to fix it. I've also noticed that this happens on both Firefox, IE, Chrome.

Anyone could help me out?

Answer

c-smile picture c-smile · Apr 30, 2011

NodeList is a live collection and non-deferred scripts execute immediately (see script defer).

Try this and you will get an idea of what happens:

<html>
<head>
  <title></title>
  <style></style>
  <script type="text/javascript">
    var elements = document.getElementsByTagName("div");
    alert(elements.length); 
  </script>
</head>
<body>
  <div>1</div>
  <script type="text/javascript">
    //var elements = document.getElementsByTagName("div");
    alert(elements.length); 
  </script>
</body>
</html>