-2

Here's the code:

/*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>
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120

1 Answers1

0

Run the js after document ready .use with window.onload function

window.onload=function(){
var btn = document.getElementsByTagName('button');
alert(btn.length);
}
<button>Games</button>
<button>Foods</button>
<button>Movies</button>
prasanth
  • 19,775
  • 3
  • 25
  • 48