"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Handle Event Listeners for Dynamically Created Elements Without jQuery?

How to Handle Event Listeners for Dynamically Created Elements Without jQuery?

Published on 2024-11-12
Browse:656

How to Handle Event Listeners for Dynamically Created Elements Without jQuery?

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.

Release Statement This article is reprinted at: 1729566794 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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