Solution 1 :

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
}

Solution 2 :

In addition to your answer If you use 1st option:
1. Adding innerHTML will trigger DOM update immediately
2. If you need to update content of newly created element you should either select it from DOM or update parent’s innerHTML again (will cause rerender, and potential lost of event listeners, if there any on a child element)

Problem :

I wonder what is the difference between creating HTML by innerHTML and document.createElement?

For example, I want to create a new DIV inside of parent DIV.

Let’s assume parent DIV has no content.

One option is parent.innerHTML = '<div></div>';

Another option is parent.append(document.createElement('div'));

I was asked this during an interview.

Personally, I think that creating an HTML object gives us the flexibility to add more elements later on compared to using innerHTML.

Wondering if there is a better reason.

By