Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

87
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda