Event Listener for Dynamically Created Elements
To add event listeners to dynamically generated elements without jQuery, you can employ event delegation. Here's how:
Use Event Delegation
The target property of the event object allows you to identify which element the event occurred on. Using this, you can bind an event listener to a parent element and check the target element to respond to specific criteria. For example:
document.querySelector('body').addEventListener('click', function(event) {
if (event.target.tagName.toLowerCase() === 'li') {
// Do your action on the newly created 'li'
}
});
In this example, the event listener is bound to the body, and when a click occurs on any child element, the code checks if it's an 'li'. If so, the specified action is performed.
Caveats
Note that this approach works well with modern browsers that support the event delegation mechanism. For older IE versions, you may need to implement a custom event handler using attachEvent.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3