Skip to main content

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.

HTML

<div class=div> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <button>Button 4</button> </div> 

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>
const array = document.querySelectorAll(".div"); array.forEach(button => { button.addEventListener('click', function (){ console.log(this.textContent) }) }); 
 

I Used a for loop and a for each loop. None worked.

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.

HTML

<div class=div> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <button>Button 4</button> </div> 

JavaScript

const array = document.querySelectorAll(".div"); array.forEach(button => { button.addEventListener('click', function (){ console.log(this.textContent) }) }); 

I Used a for loop and a for each loop. None worked.

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.

Source Link

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.

HTML

<div class=div> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <button>Button 4</button> </div> 

JavaScript

const array = document.querySelectorAll(".div"); array.forEach(button => { button.addEventListener('click', function (){ console.log(this.textContent) }) }); 

I Used a for loop and a for each loop. None worked.