Reputation: 39
So I have a bunch of divs created dynamically and I have to remove the parent elements of the ones I clicked the remove button on. Here is my code:
function add() {
let newBook = new addBookToLibrary(`"${author.value}"`, `${title.value}`, `${pages.value} pages`);
// create a div when clicked submit
// and give it class 'card', append to main-container
card = document.createElement('div');
main.appendChild(card);
card.classList.add('card');
cards = document.querySelectorAll('.card');
// append book info to card container
for (let i = 0; i < Object.keys(newBook).length; i++) {
div = document.createElement('div');
card.appendChild(div);
cardDiv = document.querySelectorAll('.card:last-child div');
cardDiv[i].textContent = Object.values(newBook)[i];
}
// create a remove button
remove = document.createElement('div');
remove.textContent = 'Remove';
remove.classList.add('remove');
card.appendChild(remove);
//event listener
remove.addEventListener('click', () => {
cards.forEach(card => card.remove());
})
};
submit.addEventListener('click', add);
This removes all cards when I click remove button. And when I try this approach:
remove.addEventListener('click', () => {
cards.forEach(card => this.card.remove());
It will only remove the last card div. Please help me fix this one.
Upvotes: 0
Views: 498
Reputation: 124
have you tried this?
remove.addEventListener('click', (event) => {
event.target.parentElement.remove();
}
Upvotes: 1