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:
<code class="javascript">document.querySelector('body').addEventListener('click', function(event) { if (event.target.tagName.toLowerCase() === 'li') { // Do your action on the newly created 'li' } });</code>
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.
The above is the detailed content of How to Handle Event Listeners for Dynamically Created Elements Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!