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?
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?
Share Improve this question edited May 23, 2017 at 12:24 CommunityBot 11 silver badge asked Apr 30, 2011 at 21:32 mobiusmobius 5,1742 gold badges29 silver badges43 bronze badges 4- Can't quite remember for sure, but try doing elements.length() - length may be a function, can't remembe.r – Thomas Shields Commented Apr 30, 2011 at 21:41
- 1 Are you sure you are calling your code when the document/DOM is loaded? It might be, that while calling getElementsByTagName, no input elements exist, but since NodeLists are dynamic, when the document loads, elements will contain all 28 inputs. – Rafael Commented Apr 30, 2011 at 21:44
- 1 It would seem that DOM isn't loaded. Copy and paste this in the URL of your page to see what it is after DOM loads. javascript:var elements=document.getElementsByTagName("input");alert("elements has "+elements.length+" children"); – adorablepuppy Commented Apr 30, 2011 at 21:48
- You are right, it's because the DOM isn't loaded. Thanks both Rafael, and adorablepuppy! – mobius Commented Apr 30, 2011 at 22:04
3 Answers
Reset to default 11NodeList
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>
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>
your script should have the attribute "deter" to detect the tags