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

How to Event Listen on Dynamically Created Elements without jQuery?

Mary-Kate Olsen
Release: 2024-10-23 00:59:03
Original
862 people have browsed it

How to Event Listen on Dynamically Created Elements without jQuery?

Event Listening on Dynamically Created Elements without jQuery

When working with external pages, adding event listeners to dynamically generated elements can prove challenging. Delegating event handling is crucial in such scenarios.

One approach is to use the event.target property to check if the clicked or triggered element is of the desired type. Here's an example:

<code class="javascript">document.querySelector('body').addEventListener('click', function(event) {
  if (event.target.tagName.toLowerCase() === 'li') {
    // Execute desired action on encountered 'li' elements
  }
});</code>
Copy after login

Note: This approach assumes that your desired elements are within the element. Adjust the selector accordingly if they're nested within other containers.

Caveats:

  • This method only applies to standards-compliant browsers (e.g., IE9 ).
  • For older IE versions (e.g., IE8), a custom wrapper around the proper native functions using attachEvent may be necessary.

The above is the detailed content of How to Event Listen on Dynamically Created 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
Latest Articles by Author
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!