通过 DOM 函数附加新元素,或用 HTML 标签附加字符串,哪个更好? [英] What is better, appending new elements via DOM functions, or appending strings with HTML tags?

查看:24
本文介绍了通过 DOM 函数附加新元素,或用 HTML 标签附加字符串,哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过几种不同的方法来向 DOM 添加元素.例如,最流行的似乎是

I have seen a few different methods to add elements to the DOM. The most prevelent seem to be, for example, either

document.getElementById('foo').innerHTML ='<p>Here is a brand new paragraph!</p>';

newElement = document.createElement('p');
elementText = document.createTextNode('Here is a brand new parahraph!');
newElement.appendChild(elementText);
document.getElementById('foo').appendChild(newElement);

但我不确定做任何一个的好处.关于何时应该完成另一个任务,或者其中之一完全错误,是否有经验法则?

but I'm not sure of the advantages to doing either one. Is there a rule of thumb as to when one should be done over the other, or is one of these just flat out wrong?

推荐答案

一些注意事项: