我有以下 javascript:
// create a new article tag
var elem = document.createElement('article');
// append the article to the comments list
document.querySelector('#comments-list').appendChild(elem);
我想设置文章的内容,并向其中添加一些类,所以我正在寻找两种方法:
// 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>";
两者都很好,但我注意到 .innerHTML
需要在元素附加到 DOM 之前调用,而 outerHTML
需要在添加到 DOM 之后调用DOM。
我更喜欢第二个选项,因为我实际上是在这个 javascript 文件中渲染 Rails 部分,并且有一个微妙的情况,它更可取。
我的问题是这些技术中的一种是否优于另一种?向 DOM 添加元素然后更改它的 HTML 是否有问题?或者从性能的 Angular 来看,在写入 DOM 之前设置 innerHTML 是否更好?
最佳答案
取自MDN-站点:
内部HTML
Element.innerHTML
属性设置或获取描述元素后代的 HTML 语法。
Note: If a
<div>
,<span>,
or<noembed>
node has a child text node that includes the characters(&), (<),
or(>)
,innerHTML
returns these characters as &, < and > respectively. UseNode.textContent
to get a correct copy of these text nodes' contents.
外部HTML
outerHTML
element
的属性DOM 接口(interface)获取描述元素(包括其后代)的序列化 HTML 片段。它可以设置为用从给定字符串解析的节点替换元素。
innerHTML 与 outerHTML:
使用 innerHTML
作为默认值。这仅替换当前元素引用的内部内容(如果使用“=”)。如果您使用 outerHTML
,那么所引用的元素将也被替换。
演示:
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>
关于Javascript innerHTML 与 outerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941911/