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

后端 未结 3 1422
天命终不由人
天命终不由人 2020-12-07 06:15

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



        
3条回答
  •  無奈伤痛
    2020-12-07 07:08

    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:

    document.body.insertAdjacentHTML('beforeend',newHtmlText);
    

提交回复
热议问题