这是代码。谢谢你的帮助。
/*this code works fine in code snippet and (when I run the code in the chrome console but when I write the code in my file.js, this won't work*/
var btn = document.getElementsByTagName('button');
alert(btn.length);
// it must alert 3, but I always get 0. Please help me. Thank you
<button>Games</button>
<button>Foods</button>
<button>Movies</button>
答案 0 :(得分:0)
在文档就绪后运行js。使用window.onload
函数
window.onload=function(){
var btn = document.getElementsByTagName('button');
alert(btn.length);
}
<button>Games</button>
<button>Foods</button>
<button>Movies</button>