x.innerHTML += y
Sometimes, we want to add a new DOM element to the HTML body dynamically, for example, add a popup Modal, like this:
document.body.innerHTML += `<div class="dnx-modal-overlay" id="dnx-modal-overlay"></div>
<div class="dnx-modal" id="dnx-modal">
<a href="#" class="close-button" id="dnx-close-button"></a>
<div class="modal-guts">
Hello! I am Pop.
</div>
</div>`;
It seems to be working as the modal is open, but after that, we see all Javascript events on the page are broken. This is because x.innerHTML += y
completely overwrites the old HTML document, although it looks the same, under the hood all Javascript events are wiped off.
The correct way to do this is using document.body.appendChild(Ele)
, like this,
const dnxModal = document.createElement("div");
dnxModal.id = "dnx-modal-wrapper";
dnxModal.innerHTML += `<div class="dnx-modal-overlay" id="dnx-modal-overlay"></div>
<div class="dnx-modal" id="dnx-modal">
<a href="#" class="close-button" id="dnx-close-button"></a>
<div class="modal-guts">
Hello! I am Pop.
</div>
</div>`;
document.body.appendChild(dnxModal);