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?