Why did alert and console.log all fail?

html part

<button id="b1" order="3">b1</button>
<button id="b2" order="4">b2</button>
<button id="b3" order="5">b3</button>

js part

var  bs = document.getElementsByTagName("button");
for(var i=0;i<bs.length;iPP){
  bs[i].addEventListener("click",getInfo);
}
function getInfo(e){
  alert(e.target.getAttribute("order"));
}

the above code can be run in jsfiddle.net.

Click b2, alert shows 4.

1. Now save it as a test.html file, open it with firefox, click b2, and no alert pops up.

2.console.log

var  bs = document.getElementsByTagName("button");
for(var i=0;i<bs.length;iPP){
  bs[i].addEventListener("click",getInfo);
}
function getInfo(e){
  console.log(e.target.getAttribute("order"));
}

change alert to console.log, click b2 not shown in the console, why?

Mar.16,2021

js definition needs to be followed by the html tag


your js code should be written at the bottom of the html, there is a problem with the order of execution.

Menu