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

88
Visualizações
Capturing events in dynamically generated HTML

I'm trying to bind an event to a piece of HTML using pure JavaScript. This is very easy when using jQuery:

$( '#item-wrapper' ).on( 'click', '.item', function () { // code here} );

Normally a user binds an action to a single element. However in my case, I need to bind an event to an entire HTML block ( the .item ). I will have random number of .item inserted into the #item-wrapper and I want to be able to capture a click on an individual .item no matter which area of that .item is clicked.

Here's what I'm using right now:

document.getElementById( '#item-wrapper' ).addEventListener( 'click', event => {
    if ( event.target && event.path ) {
        
        let itemIndex = event.path.findIndex( element => {
            if ( element.classList ) {
                return element.classList.contains( '.item' );
            }
        } );

        if ( -1 < itemIndex ) {
            // Perform actions here
        }
    }
} );

This works just fine, but I'm wondering if this is the right way to do it. I tried enabling capturing, but it's not working as the main event is registered on the #item-wrapper, and the .item are inside this block.

Is there anything I'm missing here?

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

0

const elements = document.getElementsByClassName('item')

if (elements.length > 0) {
  elements.forEach((element) => {
    element.addEventListener('click', () => {
      // actions here
    }
  }
}
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