Using .insertAdjacentHTML()
preserves event listeners, and is supported by all major browsers. It’s a simple one-line replacement for .innerHTML
.
var html_to_insert = "<p>New paragraph</p>";
// with .innerHTML, destroys event listeners
document.getElementById('mydiv').innerHTML += html_to_insert;
// with .insertAdjacentHTML, preserves event listeners
document.getElementById('mydiv').insertAdjacentHTML('beforeend', html_to_insert);
The 'beforeend'
argument specifies where in the element to insert the HTML content. Options are 'beforebegin'
, 'afterbegin'
, 'beforeend'
, and 'afterend'
. Their corresponding locations are:
<!-- beforebegin -->
<div id="mydiv">
<!-- afterbegin -->
<p>Existing content in #mydiv</p>
<!-- beforeend -->
</div>
<!-- afterend -->