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

How Can You Listen for Events on Dynamically Created Elements Without Using jQuery?

Linda Hamilton
Release: 2024-10-22 12:59:03
Original
469 people have browsed it

How Can You Listen for Events on Dynamically Created Elements Without Using jQuery?

How to Add Event Listeners to Dynamically Created Elements

When working on web pages that incorporate dynamic content, it may be necessary to add event listeners to elements that are not present on the page initially. This guide outlines a method for achieving this without relying on jQuery.

The original approach involved utilizing doc.body.addEventListener('click') to handle events for existing elements on page load. However, for dynamically generated elements, a more robust solution is required.

Delegation and Event Propagation

The key to dynamically adding event listeners is event delegation. With this approach, you can attach a single event listener to a parent element (e.g., the body) and then check the target of the event to determine the specific element that was clicked on.

Sample Code

<code class="javascript">document.querySelector('body').addEventListener('click', function(event) {
  if (event.target.tagName.toLowerCase() === 'li') {
    // Perform actions specific to 'li' elements
  }
});</code>
Copy after login

In this example, an event listener is attached to the body. When an element within the body is clicked, the target of the event is examined. If the target is an li element, the desired actions are performed.

Caveats

Note that the provided code is compatible with modern browsers. For browser compatibility with older versions of Internet Explorer, a custom wrapper around the native event functions may be required.

The above is the detailed content of How Can You Listen for Events on Dynamically Created Elements Without Using 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!