Few differences:
innerHTML
works with htmlString where as createElement()
method creates the HTML element specified by tagName. And clearly string differs to HTML element.
Events attached with innerHTML
are removed if use =+
as this redraws the full html but events attached to the element created bycreateElement()
are not lost.
Demo:
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
}