通过innerHTML和document.createElement创建HTML有什么区别?

时间:2020-02-19 22:49:30

标签: javascript html innerhtml

我想知道用innerHTML和document.createElement创建HTML有什么区别?

例如,我想在父级DIV中创建一个新的DIV。

我们假设父DIV没有内容。

一个选项是parent.innerHTML = '<div></div>';

另一个选项是parent.append(document.createElement('div'));

在面试中被问到这个

我个人认为,与使用innerHTML相比,创建HTML对象使我们可以灵活地在以后添加更多元素。

想知道是否有更好的理由。

2 个答案:

答案 0 :(得分:1)

很少有差异:

innerHTML与htmlString一起使用,其中createElement()方法创建 tagName 指定的HTML元素。很明显,字符串 HTML元素不同。

如果使用innerHTML,则与=+关联的事件将被删除,因为这会重绘完整的html,但是与createElement()创建的元素关联的事件不会丢失。

演示:

document.body.innerHTML += '<div id="first">Clicking on this will not show alert as this is created with innerHTML</div>';
document.getElementById('first').addEventListener('click', function (){
  alert('hi'); // will not work
});
document.body.innerHTML += '<div>Created again with innerHTML</div>';


var newDiv = document.createElement("div");
newDiv.id = "second";
newDiv.textContent = 'Clicking on this will show alert as this is created with createElement()';
document.body.append(newDiv);
document.getElementById('second').addEventListener('click', function (){
  alert('Hi...'); // will not work
});
var newDiv2 = document.createElement("div");
newDiv2.textContent = 'Created with createElement() again';
document.body.append(newDiv2);
div{
  padding: 5px 10px;
  border: 2px solid gray;
  background-color: lightblue
}

答案 1 :(得分:0)

除了您的答案外,如果您使用第一种选择: 1.添加innerHTML将立即触发DOM更新 2.如果您需要更新新创建元素的内容,则应该从DOM中选择它,或者再次更新父元素的innerHTML(如果子元素上有任何元素,则将导致事件监听器的重新呈现和潜在丢失)