Home  >  Article  >  Web Front-end  >  How to Handle Event Listener Attachment for Dynamically Generated Elements Without jQuery?

How to Handle Event Listener Attachment for Dynamically Generated Elements Without jQuery?

DDD
DDDOriginal
2024-10-22 11:17:29351browse

How to Handle Event Listener Attachment for Dynamically Generated Elements Without jQuery?

Dynamic Event Listener Attachment

You wish to attach event listeners to dynamically generated elements on a webpage you don't own. Since you can't use jQuery, you seek an alternative solution.

Event delegation is a viable approach in this scenario. By attaching a listener to a higher-level element (e.g., body), you can capture events that bubble up from its child elements, including those created dynamically.

<code class="javascript">document.querySelector('body').addEventListener('click', function(event) {
  if (event.target.tagName.toLowerCase() === 'li') {
    // Perform your action on 'li' elements
  }
});</code>

In this snippet:

  • We add a click event listener to the body element.
  • When a click event occurs, we check the tagName of the event.target.
  • If the target is a
  • element, we execute the desired action.

Note that this approach relies on event bubbling. It may not work in some older browsers that don't support this mechanism. Additionally, if any dynamically generated elements are nested within other elements (e.g.,

  • within
      ), you may need to adjust the event delegation selector accordingly.

      The above is the detailed content of How to Handle Event Listener Attachment for Dynamically Generated 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