Home > Web Front-end > JS Tutorial > How Can I Prevent Event Listener Loss When Modifying innerHTML?

How Can I Prevent Event Listener Loss When Modifying innerHTML?

Patricia Arquette
Release: 2024-12-15 19:40:19
Original
533 people have browsed it

How Can I Prevent Event Listener Loss When Modifying innerHTML?

Preserving Event Listeners When Appending to innerHTML

When assigning to a parent node's innerHTML, event handlers attached to descendants may be destroyed. For instance, consider the code below:

<div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><span>
Copy after login

<script></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">mydiv = document.getElementById(&quot;mydiv&quot;); mydiv.innerHTML += &quot;bar&quot;;</pre><div class="contentsignin">Copy after login</div></div> <p></script>

Here, the onclick event handler attached to the span containing "foo" is destroyed after the assignment to mydiv.innerHTML.

To avoid this issue, use the .insertAdjacentHTML() method instead of .innerHTML. This method preserves event listeners and is supported by all major browsers.

<script></p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">var html_to_insert = "<p>New paragraph</p>";
document.getElementById('mydiv').insertAdjacentHTML('beforeend', html_to_insert);
Copy after login


The 'beforeend' argument specifies where in the element to insert the HTML content. Other options include 'beforebegin', 'afterbegin', and 'afterend'.

The above is the detailed content of How Can I Prevent Event Listener Loss When Modifying innerHTML?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Previous article:Why Doesn't `setState` Update the React Component State Immediately? Next article:Why Does `$(this)` Fail in jQuery Click Handlers with ES6 Arrow Functions?
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
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template