I am attempting to add event listeners to all of the buttons in an HTML document. When a button is pressed I'd like to display a simple alert. My code, which isn't working at the moment, follows:
var bns = document.getElementsByTagName("button");
function addtoev() {
for (i = 0; i < bns.length; i++) {
bns[i].addEventListener("click", function() {
alert("you clicked");
});
}
}
It definitely works as such in JSFiddle by calling the method or eliminating the function line, but it's still not executing in Chrome (popups are not blocked). I post my HTML, is it possible that buttons nested in a table need to be referenced differently than buttons alone?
<tr>
<td>John</td>
<td>Doe</td>
<td>john@doe.us</td>
<td><button class="btn btn-default">X</button></td>
</tr>