Home >Web Front-end >JS Tutorial >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><pre class="brush:php;toolbar:false"><span>
<script></p>
<pre class="brush:php;toolbar:false">mydiv = document.getElementById("mydiv");
mydiv.innerHTML += "bar";</pre>
<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> <pre class="brush:php;toolbar:false">var html_to_insert = "<p>New paragraph</p>"; document.getElementById('mydiv').insertAdjacentHTML('beforeend', html_to_insert);
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!