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
.