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

vanilla js onclick remove parent element

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.

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 :

have you tried this?

remove.addEventListener('click', (event) => {
 event.target.parentElement.remove();
}
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