NodeList.length is always returning 0

7.7k views Asked by At

I have a NodeList object that is created by

var buttons = document.getElementsByName("signupButton");

console.log(buttons);

prints

[item: function]
0: button.btn.btn-warning.btn-lg
1: button.btn.btn-warning.btn-lg
2: button.btn.btn-warning.btn-lg
length: 3
__proto__: NodeList

But buttons.length is printing 0. What is going on here?

1

There are 1 answers

0
msecret On

This is happening because the DOM has not loaded yet when your JS is executing. The reason its showing up in the console is because chrome, or maybe firefox, will update the console when the DOM changes, essentially changing the output in the console.

In order for this to work, you have two options:

  • register an event handler for when the DOM is loaded and execute this code then.

    document.addEventListener('DOMContentLoaded', function(){ // the code //make AJAX request when button is clicked var buttons = document.getElementsByName("signupButton"); });

  • move this script tag right before the closing tag to ensure the DOM will have loaded when it gets executed.

    </body> <script> // the code </script>