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


Yes, it is possible to append to innerHTML without destroying descendants event listeners. Let us see an example. First, we will create two functions with JavaScript. Here’s the demoFunc() −

function demoFunc() {
   alert("Hello");
}

The function demoFunc() above will display an alert box and a message. With that, the start() function loads when you load the web page and displays “Two” with “One” in the div. Here’s the start() function. We have appended the text “One” from the div with the text “Two” using the innerHTML property −

function start() {
   mydiv.innerHTML += "Two";
}

Following is our HTML code, that calls the start() when the web page loads using the −

<body onload="start()">

The div id is mydiv, styled with the orange background −

<div id="mydiv" style="background:orange;">

Within the <div>, the <span> calls the demoFunc() using the onlick −

<body onload="start()">
   <div id="mydiv" style="background:orange;">
      <span id="myspan" onclick="demoFunc()">One</span>
   </div>
</body>

Example

Let us now see the complete example to append to innerHTML −

<!DOCTYPE html>
<html>
<head>
   <title>Example</title>
</head>
<body onload="start()">
   <div id="mydiv" style="background:orange;">
      <span id="myspan" onclick="demoFunc()">One</span>
   </div>
</body>
<script>
   function start() {
      mydiv.innerHTML += "Two";
   }
   function demoFunc() {
      alert("Hello");
   }
</script>
</html>

Output

On clicking “One”, the alert box displays −

Updated on: 06-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements