Addeventlistener For Loop Doesn't Respond
Solution 1:
It doesn't work because p1button
is already an ElementButton
, not an Array where you have to use [0]
to get the element from.
var p1button = document.querySelector("#p1");
p1button.addEventListener("click", function(){
alert("clicked")
});
<buttonid="p1">Player One</button>
whereas, is you had multiple class.btn
elements your code would make sense, since .getElementsByClassName
or .querySelectorAll
do actually return an array-likeNodeList:
functiondoThaChng () {
alert("clicked!");
}
var btn = document.querySelectorAll(".btn");
for(var i=0; i<btn.length; i++) {
btn[i].addEventListener("click", doThaChng);
}
<buttonclass="btn">Player One</button><buttonclass="btn">Player Two</button>
Or in ES6
const btn = document.querySelectorAll(".btn");
constdoThaChng = () => alert("Clicked");
[...btn].forEach(el => el.addEventListener("click", doThaChng) );
<buttonclass="btn">Player One</button><buttonclass="btn">Player Two</button>
Solution 2:
p1button
is not an array but a DOM element.
Try keeping just:
p1button.addEventListener("click", function(){
alert("clicked")
});
Solution 3:
From the documentation of querySelector()
:
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
Try it out (open up Developer Tools to see the console):
console.log(document.querySelector("button"));
So you don't need (and you can not) iterate over p1button
, because it's a node instead of an array.
Solution 4:
It's because querySelector
and getElementById
returns a single DOM element and not an array of DOM elements. So your for loop is useless and try to add an event listener on an undefined
value.
Here is a correct way to listen for click event
var p1button = document.querySelector("#p1");
p1button.addEventListener("click", function(){
alert("clicked")
});
Here you can find more infos about querySelector and getElementById.
Post a Comment for "Addeventlistener For Loop Doesn't Respond"