Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
Captura de eventos en HTML generado dinámicamente

Estoy tratando de vincular un evento a una pieza de HTML usando JavaScript puro. Esto es muy fácil cuando se usa jQuery:

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

Normalmente, un usuario vincula una acción a un solo elemento. Sin embargo, en mi caso, necesito vincular un evento a un bloque HTML completo (el .item ). Tendré un número aleatorio de .item insertado en el #item-wrapper y quiero poder capturar un clic en un .item individual sin importar en qué área de ese .item se haga clic.

Esto es lo que estoy usando ahora mismo:

 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 } } } );

Esto funciona bien, pero me pregunto si esta es la forma correcta de hacerlo. Intenté habilitar la captura, pero no funciona porque el evento principal está registrado en #item-wrapper y los .item están dentro de este bloque.

¿Hay algo que me estoy perdiendo aquí?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!