Javascript innerHTML 与 outerHTML

新手上路,请多包涵

我有以下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 之后调用。

我更喜欢第二个选项,因为我实际上是在这个 javascript 文件中渲染 Rails partials,并且有一个微妙的情况,它更可取。

我的问题是这些技术中的一种是否比另一种更好?向 DOM 添加元素然后更改它的 HTML 是否有问题?或者从性能的角度来看,在写入 DOM 之前设置 innerHTML 是否更好?

原文由 stephenmurdoch 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 350
2 个回答

取自 MDN 站点:

内部HTML

  • Element.innerHTML 属性设置或获取描述元素后代的 HTML 语法。

Note: If a <div> , <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>) , innerHTML 将这些字符返回为 &amp、&lt 和 &gt。使用 Node.textContent 获取这些文本节点内容的正确副本。

外部HTML

element DOM 接口的 outerHTML 属性获取描述元素(包括其后代)的序列化 HTML 片段。它可以设置为用从给定字符串解析的节点替换元素。

innerHTMLouterHTML

使用 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>

原文由 ravo10 发布,翻译遵循 CC BY-SA 3.0 许可协议

我会说两者可能都不是您想要的,请使用 textContent 或任何处理元素文本的属性。

 elem.textContent = "This is the comment";
elem.classList.add("comment");

innerHTML 将内容解析为 HTML 并完全销毁元素并重新创建它,它还销毁可能为该元素注册的任何事件处理程序等。使用 outerHTML,元素集仍将保留对原始元素(如果有)的引用。

因此,与设置文本内容的正确属性相比,两者都有可能产生意想不到的副作用。

原文由 Fraser 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏