Javascript 内层 HTML 与外层 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46941911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript innerHTML vs outerHTML
提问by stephenmurdoch
I have the following javascript:
我有以下 javascript:
// create a new article tag
var elem = document.createElement('article');
// append the article to the comments list
document.querySelector('#comments-list').appendChild(elem);
I want to set the content of the article, and add some classes to it too so I'm looking at two ways of doing this:
我想设置文章的内容,并向其中添加一些类,因此我正在研究两种方法:
// Option 1
// set the content using .innerHTML()
// and add the classes manually to the classList
elem.innerHTML = "This is the comment";
elem.classList.add('comment');
// Option 2
// set the content and classes in one go using .outerHTML()
elem.outerHTML = "<article class='comment'>This is the comment</article>";
Both work great, but I notice that .innerHTMLneeds to be called before the element is appended to the DOM, wheras outerHTMLneeds to be called after it added to the DOM.
两者都很好用,但我注意到.innerHTML需要在将元素附加到 DOM 之前outerHTML调用它,而需要在将元素添加到 DOM之后调用它。
I prefer the second option because I'm actually rendering Rails partials in this javascript file, and there's a nuanced case where it is preferable.
我更喜欢第二个选项,因为我实际上是在这个 javascript 文件中渲染 Rails 部分,并且有一个微妙的情况,它更可取。
My question is whether one of these techniques is better than the other? Is is a problem to add an element to the DOM and then change it's HTML afterwards? Or is it better from a perfomance standpoint to set innerHTML before writing to the DOM?
我的问题是这些技术中的一种是否比另一种更好?将元素添加到 DOM 然后再更改它的 HTML 是否有问题?或者从性能的角度来看,在写入 DOM 之前设置 innerHTML 更好吗?
采纳答案by ravo10
Taken from the MDN-site :
摘自MDN站点:
innerHTML
内部HTML
- The
Element.innerHTMLproperty sets or gets the HTML syntax describing the element's descendants.
- 该
Element.innerHTML属性设置或获取描述元素后代的 HTML 语法。
Note: If a
<div>,<span>,or<noembed>node has a child text node that includes the characters(&), (<),or(>),innerHTMLreturns these characters as &, < and > respectively. UseNode.textContentto get a correct copy of these text nodes' contents.
注意:如果
<div>,<span>,or<noembed>节点有一个包含字符(&), (<),or的子文本节点(>),则分别innerHTML将这些字符作为 &、< 和 > 返回。使用Node.textContent获得的这些文本节点的内容的正确副本。
outerHTML
外部HTML
The outerHTMLattribute of the elementDOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.
DOM 接口的outerHTML属性element获取描述元素(包括其后代)的序列化 HTML 片段。它可以设置为用从给定字符串解析的节点替换元素。
innerHTMLvs. outerHTML:
innerHTML与externalHTML:
Use innerHTMLas default. This replaces onlythe content (if using i.e. "=") insidethe current element referred to. If you are using outerHTML, then the elementreferred to will alsobe replaced.
innerHTML默认使用。这仅替换所引用的当前元素内的内容(如果使用即“=”)。如果您正在使用outerHTML,那么元素提及将也被替换。
Demo:
演示:
var h20 = document.getElementById("h20"),
h21 = document.getElementById("h21");
var ran = false;
console.log("'h20' innerHTML (1) =", "'" + h20.innerHTML + "'", "outerHTML (1) =", "'" + h20.outerHTML + "'");
console.log("'h21' innerHTML (1) =", "'" + h21.innerHTML + "'", "outerHTML (1) =", "'" + h21.outerHTML + "'");
document.getElementById("button").onclick = evt => {
if (ran) return false;
h20.innerHTML = "<div>innerHTML</div>";
h21.outerHTML = "<div>outerHTML</div>";
console.log("'h20' innerHTML (2) =", "'" + h20.innerHTML + "'", "outerHTML (2) =", "'" + h20.outerHTML + "'");
console.log("'h21' innerHTML (2) =", "'" + h21.innerHTML + "'", "outerHTML (2) =", "'" + h21.outerHTML + "'");
ran = true
}
<button id="button">innerHTML vs. outerHTML</button>
<br>
<h2 id="h20"></h2>
<h2 id="h21"></h2>
回答by Fraser
I'd say both are probably not what you want, use textContent or else whatever property handles the text for the element.
我想说两者都可能不是你想要的,使用 textContent 或其他任何处理元素文本的属性。
elem.textContent = "This is the comment";
elem.classList.add("comment");
innerHTML parses content as HTML and completely destroys the element and recreates it, it also destroys any event handlers, etc that might be registered for the element. With outerHTML the element set will still hold a reference to the original element (if any).
innerHTML 将内容解析为 HTML 并完全销毁元素并重新创建它,它还销毁可能为该元素注册的任何事件处理程序等。使用outerHTML,元素集仍将保留对原始元素(如果有)的引用。
So both have possible unintended side-effects vs the correct property to set text content.
因此,与设置文本内容的正确属性相比,两者都有可能出现意想不到的副作用。
回答by Paul Wratt
According to the OP questions, its comments, and the one good answer, in this instance you are better off using elem.outerHTMLbecause you are/can pre-parse your input in Rails.
根据 OP 问题、其评论和一个好的答案,在这种情况下,您最好使用,elem.outerHTML因为您/可以在 Rails 中预先解析您的输入。
If you were to move decision making to the JavaScript side, good coding practicewould dictate creating all nodes by hand. If you are processing 100's of element inserts then you will notice a difference in speed (if you were to benchtest both solutions).
如果您要将决策转移到 JavaScript 端,好的编码实践将要求手动创建所有节点。如果您正在处理 100 个元素插入,那么您会注意到速度上的差异(如果您要对两种解决方案进行基准测试)。

