Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access buttons of a div as an array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can access the event.target to get the context of the click.

document.querySelectorAll('.my-div').forEach(function(button) {
  button.addEventListener('click', function(event) {
    console.log(event.target.textContent)
  })
});
<div class="my-div">
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
</div>

Even better, you could delegate the event and reuse the listener for any button that matches the selector.

document.querySelector('.my-div').addEventListener('click', function(event) {
  if (event.target.matches('button')) {
    handleClick(event);
  }
});

function handleClick(event) {
  console.log(event.target.textContent);
}
<div class="my-div">
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading