Yuval Dikerman
Yuval Dikerman

Reputation: 1

forEach loop only works on the last item

I'm trying to add a button the multiple divs on a page. Why does it work only on the last item?

const columns = document.querySelectorAll('.hcolumn');
const button = document.createElement('div');
button.innerText = 'Expand text';
button.classList.add ('button');

columns.forEach( column => {
column.append(button)
});

Here's the codepen

Upvotes: 0

Views: 608

Answers (1)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

That's because you're are appending the same button element each time which is a single reference so it gets removed from previous element and gets appended to next one. You also need to create a new button everytime like so :-

const columns = document.querySelectorAll('.hcolumn');

columns.forEach( column => {
const button = document.createElement('div');
button.innerText = 'Expand text';
button.classList.add ('button');
column.append(button)
});

Upvotes: 4

Related Questions