Cannot select class using JavaScript

Cannot select class using JavaScript


Hi guys.
I’m trying to select the “mole” class in my “wack-a-mole” application using JavaScript, but its not working for some reason.

Here is my code:


querySelectorAll() returns an array-like object. addEventListener only works on a single DOM element. So, you will need to loop over the querySelectorAll() result and call addEventListener for all of them.


A different approach would be to add one event listener to the “game” div and then use to access the div clicked. This approach is referred to as event delegation.

const game = document.getElementById("game");
game.addEventListener("click", (event)=> {
  if ("class") === "mole") 
    alert("Hi, you clicked a mole.");
    alert("Hi, you clicked a hole.")


why doesn’t this work?

mole.forEach = e => {
  e.addEventListener("click", ()=> {


I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard.

In the above code, you are attempting to creating a property called “forEach” which is a function.

Instead, you need to supply a function as the argument for the forEach function as:

mole.forEach(e => {
  e.addEventListener("click", ()=> {