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