Does anyone know why if you use document.body.innerHTML += \"content\";
the JavaScript on the page stops working? I have the following code:
As has been explained by others, using:
document.body.innerHTML += newHtmlText;
deletes the entire page and recreates it. This causes:
.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.This will almost certainly completely break most already existing JavaScript.
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:
document.body.insertAdjacentHTML('beforeend',newHtmlText);