"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Event Listen on Dynamically Created Elements without jQuery?

How to Event Listen on Dynamically Created Elements without jQuery?

Published on 2024-11-06
Browse:267

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:

document.querySelector('body').addEventListener('click', function(event) {
  if (event.target.tagName.toLowerCase() === 'li') {
    // Execute desired action on encountered 'li' elements
  }
});

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.
Release Statement This article is reprinted at: 1729566436 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3