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

86
Views
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 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!