Reputation: 1
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
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