Cannot select class using JavaScript

Cannot select class using JavaScript
0

#1

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:
https://codepen.io/Modestas/pen/LjOqjM/


#2

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.


#3

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

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

#4

why doesn’t this work?

mole.forEach = e => {
  e.addEventListener("click", ()=> {
    alert("Hi");
  })
}

#6

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", ()=> {
    alert("Hi")
  });
});