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 would throw domexception.
- e.g. [Chrome Dev Console] document.documentelement.outerhtml= ' a '; uncaught domexception: Failed to sets the ' outerHTML ' property in ' Element ': this element ' s parent is of type ' #document ', which is isn't 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 is replaced in the document, the variable whose property is outerHTML set to still hold a reference To the original element!
InnerText and Outertext
- Node.innertext
- Non-standard:do not use it on production site.
- Htmlelement.outertext
- Non-standard:do not use it on production site.
| Feature |
Chrome |
Firefox (Gecko) |
Internet Explorer |
Opera |
Safari (WebKit) |
| Basic Support |
4 |
45 (45) |
6 |
9.6 (probably earlier) |
3 |
Textcontent V.s InnerText
- Node.textcontent
- G et: different node types gets different result
- Null: document, Notation (use document.documentElement.textContent instead).
- Text inside the node: CDATA, Comment, text node, processing instruction. (NodeValue)
- Concatenation of children nodes (excluding comment, processing instruction nodes) text:other types node
- Set: Remove node children and replace it with a text node.
- Difference from InnerText
- Why we still need innerText sometime?
- Browser compatibility!
- IE has better support for InnerText than for textcontent. Only ie9+ supports textcontent, but ie6+ supportsinnerText.
- Common usage:
Textcontent V.s. InnerHTML
- It ' s recommand to use textcontent!
- InnerHTML Parse text as HTML (except "script" element), poor performance!
- InnerHTML has security problem!
innerhtml/outerhtml; Innertext/outertext; Textcontent