我有以下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 许可协议
取自 MDN 站点:
内部HTML
Element.innerHTML
属性设置或获取描述元素后代的 HTML 语法。外部HTML
element
DOM 接口的outerHTML
属性获取描述元素(包括其后代)的序列化 HTML 片段。它可以设置为用从给定字符串解析的节点替换元素。innerHTML 与 outerHTML :
使用
innerHTML
作为默认值。这 仅 替换引用的当前元素 内 的内容(如果使用即“=”)。如果您使用的是outerHTML
,那么引用的 元素 也 将被替换。演示: