NodeList.length is always returning 0 [duplicate]

橙三吉。 提交于 2019-12-05 09:12:23

问题


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:


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>



来源:https://stackoverflow.com/questions/26894000/nodelist-length-is-always-returning-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!