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

Spread the love

When you use innerHTML to set HTML content, it completely replaces the existing content, including any event listeners attached to descendant elements.


To append content without destroying event listeners on existing elements, you have a few options: 1. Using insertAdjacentHTML()
This method allows you to insert HTML into the DOM at a specified position relative to the element.
2. Creating new elements and appending them
Instead of manipulating HTML strings directly, you can create new DOM elements using document.createElement() and append them to the existing elements.
To use this, we write:
// Using insertAdjacentHTML()
var container = document.getElementById('container');
container.insertAdjacentHTML('beforeend', '
New Content
'); // Creating new elements and appending them
var newDiv = document.createElement('div');
newDiv.textContent = 'New Content';
container.appendChild(newDiv);

Both of these methods allow you to append content without destroying event listeners on existing elements.
Choose the one that best fits your use case and coding style.