Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByTagName().length returns zero

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?

like image 732
mobius Avatar asked Apr 30 '11 21:04

mobius


People also ask

What is getElementsByTagName return?

getElementsByTagName() The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node.

Does getElementsByTagName return an array?

getElementsByTagName - the method name itself implies that it will return multiple elements - i.e. an array. The method always returns an array, with the length equal to the number of matching elements. As such you must always access the elements by the index of the element in the array.

What is the Syntax of getElementsByTagName()?

Syntax: var elements = document. getElementsByTagName(name);

What does getElementsByTagName do?

getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically.


2 Answers

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>
like image 64
c-smile Avatar answered Sep 30 '22 16:09

c-smile


This happens because of the asynchronous behaviour of JS. You're trying to display the element's value before it is being rendered. In order to avoid it, you could add the "async" attribute to your tag, as in the following example:

<script type="text/javascript" src="myTag.js" async></script>
like image 37
gurma Avatar answered Sep 30 '22 16:09

gurma