
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Append to innerHTML Without Destroying Event Listeners in 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 ?
