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

200
Visualizações
El botón JS onclick elimínelo del DOM que no funciona correctamente cuando tiene un subelemento adjunto

Tengo la siguiente estructura html:

 <div class="input-group mt-3 ms-3" style="max-width: 300px"> <input type="text" class="form-control form-control-sm" name="search" placeholder="Type something"/> <button type="button" class="btn btn-secondary btn-sm btn-clear-search-input" style="width: 50px"> <i class="fas fa-times"></i> </button> </div>

Y me gustaría quitar el botón después de haberlo presionado. El problema es que si el usuario presiona justo en el medio del botón (donde está el <i> ), solo elimina el <i> .

 const btnClearSearchInput = document.getElementsByClassName('btn-clear-search-input')[0]; btnClearSearchInput.addEventListener('click', clearSearch); function clearSearch(event) { event.target.remove(); }

Al ejecutar console.log() en event.target y event.srcElement , puedo ver que el valor está relacionado con <i> .

El siguiente JSFiddle ilustra el problema.

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Esto se debe a que i es el elemento sobre el que se disparó el evento y, por lo tanto, es event.target ; en su lugar usa:

 function clearSearch(event) { // the event.currentTarget is the node to // which the event-listener was bound, instead // of the event.target, which is the node // on which that the event-listener is // listening for, was initially fired: event.currentTarget.remove(); } 

 // using document.querySelector() to find, and return, the first element which // matches the supplied selector: const btnClearSearchInput = document.querySelector('.btn-clear-search-input'); btnClearSearchInput.addEventListener('click', clearSearch); function clearSearch(event) { event.currentTarget.remove(); }
 *, ::before, ::after { box-sizing: border-box; font: normal 1rem / 1.5 sans-serif; margin: 0; padding: 0; } div.input-group { display: flex; flex-direction: row; flex-wrap: nowrap; gap: 0; } i.fas.fa-times::before { content: 'X'; width: 1.5em; aspect-ratio: 1; }
 <div class="input-group mt-3 ms-3" style="max-width: 300px"> <input type="text" class="form-control form-control-sm" name="search" placeholder="Type something" /> <button type="button" class="btn btn-secondary btn-sm btn-clear-search-input"> <i class="fas fa-times"></i> </button> </div>

Referencias:

  • event.currentTarget .
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