我有以下的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 偏见,并且存在微妙的情况,其中它是首选。
我的问题是这两种技术是否有一种比另一种更好?将元素添加到 DOM 然后再更改其 HTML 是有问题的吗?还是从性能的角度来看,在写入到 DOM 之前设置 innerHTML 更好?
elem.className="comment"
即可。 - dandavis