你的位置:首页 > 网页设计

[网页设计]innerHTML/outerHTML; innerText/outerText; textContent


innerHTML v.s. outerHTML

  • Element.innerHTML
    •   Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
    •   Functionality
      •   Get serialized HTML code describing its descendants.
      •   Set : Remove all the children, parse the content string and assign the resulting nodes as the children of the element. 
  • Element.outerHTML
    •   Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
    •   Functionality
      •   Get serialized HTML fragment describling the element and its descendants.
      •   Set : Replace the element with the nodes generated by parsing the content string with parent of the element as the context node for the fragment parsing algorithm.
    •   NOTE
      •   If element has no parent element, set outerHTML will throw DOMException.
        •   e.g. [Chrome Dev Console]  document.documentElement.outerHTML='a';   Uncaught DOMException: Failed to set the 'outerHTML' property on 'Element': This element's parent is of type '#document', which is not an element node.
      •   Considering below code.
        // HTML:// <div id="container"><div id="d">This is a div.</div></div>container = document.getElementById("container");d = document.getElementById("d");console.log(container.firstChild.nodeName); // logs "DIV"d.outerHTML = "<p>This paragraph replaced the original div.</p>";console.log(container.firstChild.nodeName); // logs "P"// The #d div is no longer part of the document tree,// the new paragraph replaced it.

        While the element will be replaced in the document, the variable whose outerHTML property was set will still hold a reference to the original element!

innerText and outerText

innerHTML v.s. textContent