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

158
Visualizações
How can I propagate click events to a button from an interior span element?

I'm trying to delete parent div when button is clicked. But when I click not the button itself but the icon inside it (span), the parent element for it is the button, not div outside button. Is there any possibility to merge this span with button, so when the span is clicked it is treated as clicking the button?

Here is how button is created:

//Create trash button
const trashButton = document.createElement('button');
trashButton.innerHTML = '<span class="material-icons">delete</span>';
trashButton.classList.add('trash-button');
todoDiv.appendChild(trashButton);

//delete div of button
todoList.addEventListener('click', deleteTask);

function deleteTask(e) {
    const item = e.target;
    if (item.classList.contains('trash-button')) {
        item.parentNode.remove();
    };
    console.log(item);
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Add the eventListener directly to the button, not toDoList. That is the best option.

const trashButton = document.createElement('button');
trashButton.innerHTML = '<span class="material-icons">delete</span>';
trashButton.classList.add('trash-button');
todoDiv.appendChild(trashButton);

//delete div of button
button.addEventListener('click', deleteTask);

function deleteTask(e) {
    const item = e.target;
    //here you also will use ternary conditional to double check if you want:
    item.classList.contains("trash-button") ? item.parentNode.remove() : button.parentNode.remove();
    };
    console.log(item);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I would add the eventListner to the button directly, but otherwise u could also check the parent for the class

if (item.classList.contains('trash-button') || item.parentNode.classList.contains('trash-button')) {

or cleaner with closest

if (item.closest('.trash-button')) {

about 4 years ago · Juan Pablo Isaza 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