Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-10-22 11:17:29
Original
350 people have browsed it

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>
Copy after login

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!

  • source:php
    Statement of this Website
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!