Home  >  Article  >  Web Front-end  >  How to Handle Event Listeners for Dynamically Created Elements Without jQuery?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-22 12:08:02588browse

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:

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn