0

I have an event listener and every time I click on the element I need, I get console.log printed out twice. First time I get null or undefined, second time I get the element I need. Why is that hapenning? The code is very simple:

document.addEventListener("click", function(e) {
  var id = document.getElementById(e.target.value);
  console.log(id);
  id.style.display="block";
});
Limpuls
  • 856
  • 1
  • 19
  • 37
  • 2
    Event bubbling see https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing – Satpal Feb 21 '18 at 12:11
  • 1
    Using `<>` button you could provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) demonstrating the issue. – Yury Tarabanko Feb 21 '18 at 12:15

1 Answers1

0

Catch any click on the document, and check if the clicked element contains the class you are looking for. This also works on dynamically added elements added to the page by JavaScript after the page was loaded.

// Add click event to all buttons
document.addEventListener("click", function(event) {
  if(event.target.classList.contains("clickme")) {
    //do something with the clicked element:
    console.log("Button clicked:");
    console.log(event.target.innerHTML);
  }
});
<button class='clickme'>Button 1</button>
<button class='clickme'>Button 2</button>
  • I know that I can fix this by adding event listener directly to the element. But my element is a class and there are like 5 classes. So the element returns html collection. For that reason I get the error that even listener is not a function. When I try converting html collection to array using various methods people told me, I get empty array back. – Limpuls Feb 21 '18 at 12:35
  • So you are just looking for a click event on an element with class? Simple, I'll edit my answer. –  Feb 21 '18 at 12:54
  • Yes. I was able to move html collection to array by making sure wordpress loads my script file in the footer. Then I ran forEach loop to add event listener for each element in that array. When I try to console.log the element, I still get both undefined and element in console. Both the same line. I don't know why it prints out twice and first time it's still undefined – Limpuls Feb 21 '18 at 12:57
  • Can you maybe make a codepen.io with an HTML and JavaScript example? I will fix it right away for you. –  Feb 21 '18 at 13:21