Categories
JavaScript Answers

How to append to innerHTML without destroying descendants’ event listeners with JavaScript?

Spread the love

To append to innerHTML without destroying descendants’ event listeners with JavaScript, we need to use DOM methods.

For instance, we write

<div id="myDiv">
  <span id="mySpan">foo</span>
</div>

to add the div and span.

const mySpan = document.getElementById("mySpan");
mySpan.onclick = () => {
  alert("hi");
};

const myDiv = document.getElementById("myDiv");
myDiv.appendChild(document.createTextNode("bar"));

to get the span with getElementById.

And we add a click listener to it by setting the onclick property to the click listener.

Then we get the div with getElementById and then call appendChild on it to append a text node as its last child.

We create the text node with createTextNode.

Then span’s click listener is kept after we call appendChild.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *