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
Patricia ArquetteOriginal
2024-12-15 19:40:19534browse

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(&quot;mydiv&quot;); mydiv.innerHTML += &quot;bar&quot;;</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!

Statement:
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
Previous article:Why Doesn't `setState` Update the React Component State Immediately?Next article:Why Doesn't `setState` Update the React Component State Immediately?

Related articles

See more