getElementsByTagName().length returns zero

前端 未结 3 425
臣服心动
臣服心动 2021-01-04 20:17

I am trying to do a simple thing such as:

var elements = document.getElementsByTagName(\"input\");
console.log(elements);
console.log(elements.length);
         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 20:36

    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:

    
    

提交回复
热议问题