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>
Note: This approach assumes that your desired elements are within the
element. Adjust the selector accordingly if they're nested within other containers.Caveats:
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!