Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

328
Visualizações
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.

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

have you tried this?

remove.addEventListener('click', (event) => {
 event.target.parentElement.remove();
}
about 4 years ago · Santiago Gelvez Relatório

0

Inside the remove function: this.closest("div").remove();.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda