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');
    cards = document.querySelectorAll('.card');

    // append book info to card container
    for (let i = 0; i < Object.keys(newBook).length; i++) {
        div = document.createElement('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';

    //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.

>Solution :

have you tried this?

remove.addEventListener('click', (event) => {;

Leave a Reply