This is a problem I was having:
I am trying to access the button inside of the div and make each of them log its own text content on click. But all of them display all of the text content. And it has to be in vanilla JavaScript.
const array = document.querySelectorAll(".div");
array.forEach(button => {
button.addEventListener('click', function (){
console.log(this.textContent)
})
});
<div class=div>
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<button>Button 4</button>
</div>
I Used a for loop and a for each loop. None worked.
3
Answers
I was calling all the elements with the class .div.
What I wanted was to call the buttons inside the element with the class .div.
Solution: add 'button' after .div:
And now it works:
You can access the
event.target
to get the context of the click.Even better, you could delegate the event and reuse the listener for any button that matches the selector.
Your code is looping through the array of
div
elements and adding an event handler to thediv
element, rather than the buttons.but instead of looping through all the buttons, use "event delegation" where you set up a single handler at an ancestor of all the buttons (the
div
in this case) and check theevent.target
, which refers to the object that actually fired the event. Much simpler approach – no loops, no arrays.