[Solved] In-page JavaScript stops when I use document.body.innerHTML += newHtmlText

Does anyone know why if you use document.body.innerHTML += "content"; the JavaScript on the page stops working? I have the following code:

document.addEventListener('contextmenu', function (e) {
    try {
    } catch (x) {
    var newHtmlText = "<div id='menu'>";
    newHtmlText += "<div class="menu-item" id='menu-back' onclick='window.history.back();'>" +
        "<div class="fa fa-arrow-left icon"></div><div class="text">Back</div><div class="clear"></div></div>";
    newHtmlText += "<div class="menu-item" id='menu-forward' onclick='window.history.forward();'>" +
        "<div class="fa fa-arrow-right icon"></div><div class="text">Forward</div><div class="clear"></div></div>";
    newHtmlText += "<div class="menu-item" id='menu-reload' onclick='location.reload();'>" +
        "<div class="fa fa-repeat icon"></div><div class="text">Reload</div><div class="clear"></div></div>";
    newHtmlText += "<hr />";
    newHtmlText += "<div class="menu-item" id='menu-home' onclick='location.href = ""/"";'>" +
        "<div class="fa fa-home icon"></div><div class="text">Home</div><div class="clear"></div></div>";
    newHtmlText += "</div>";
    document.body.innerHTML += newHtmlText;
    var menu = document.getElementById('menu'); = (e.clientX) + "px"; = (e.clientY) + "px";

Every time I open the context menu the JavaScript stopped working. This is not the only time it has done this.

Enquirer: Pete


Solution #1:

Using x.innerHTML += y is equivalent to x.innerHTML = x.innerHTML + y;

This means that you are completely overwriting the old document with a new document – it may appear visually the same, but under the hood you’ve just nuked every single reference to everything.

If a bit of JavaScript elsewhere in the page used something like var container = document.getElementById('container');, in order to save a reference, well that reference is now gone.

If there are any event listeners bound to elements in the document, those are gone too because the elements were nuked and replaced with identical-looking ones.

If you want to add your context menu to the page, you should do something like:

var menu = document.createElement('div'); = 'menu';
menu.innerHTML = "Your menu HTML here";

This will add the new element to the page without nuking the whole thing.

Solution #2:

document.body.innerHTML += "content"; 

Does three things:

  1. Reads the value of innerHTML
  2. Modifies that value
  3. Overwrites innerHTML with the new value

This deletes the page and then creates a new one.

Since script elements inserted with innerHTML are not executed, this kills the JS.

Don’t append data using innerHTML. Generate DOM nodes (with createElement, createTextNode and friends) and then append them (with appendChild, insertBefore and so on).

Respondent: Quentin

Solution #3:

As has been explained by others, using:

document.body.innerHTML += newHtmlText;

deletes the entire page and recreates it. This causes:

  • All event listeners which were placed on elements to become disconnected from the DOM. If there is not some external reference to the DOM element or the listener function (e.g. a named function), the listener will be garbage collected (browser dependent).
  • Any saved references to elements will now reference elements which are no longer in the DOM. These DOM nodes, and their children, will not be garbage collected, as there is still a reference to them. The JavaScript using these references will not throw errors unless it tries to find references to associated DOM nodes to which the element is no longer connected (ancestor nodes, e.g. .parentNode). However, the JavaScript will be completely ineffective at manipulating the displayed DOM, as it will be using references to elements which are no longer in the DOM.
  • The entirety of the old DOM will be garbage collected (browser dependent), except for any elements, and their children, which have a reference saved elsewhere in JavaScript code.

This will almost certainly completely break most already existing JavaScript.

Use .insertAdjacentHTML()

The correct way to add HTML text, without disturbing the already existing contents, is to use element.insertAdjacentHTML(relativeLocation, HTMLtext). Using .insertAdjacentHTML(), you can add HTML text in four different locations relative to the referenced element. The value of relativeLocation can be:

  • 'beforebegin': Prior to the element
  • 'afterbegin': Just inside the beginning of element (like adding a new .firstChild, but you can add as many children (as much HTML text) as you desire).
  • 'beforeend': Prior to the end of the element (like .appendChild(), but you can add as many children (as much HTML text) as you desire).
  • 'afterend': Just after the element (like element.parentNode.insertBefore(newElement,element.nextSibling), but you can add as many children of the parentNode (as much HTML text) as you desire). Note: If you were inserting an element you could also use: element.insertAdjacentElement('afterend',newElement).

For what you desire to do, you would use:

Respondent: Makyen

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy