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?
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.
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.
Syntax: var elements = document. getElementsByTagName(name);
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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With