X.innerHTML vs x.appendChild?

Hello guys,

I’m just learning about HTML DOM and have the following question.

If you want to create something like: <a …><img …></a> with HTML DOM, then I believe you can do that in the following ways:

var newA = document.createElement(‘a’);
newA.innerHTML = “<img…>”;


var newA = document.createElement(‘a’);
var newI = document.createElement(‘img’);

I believe both codes will work, right? Which one is better to use? Any advantages/disadvantages when using one or the other?

The advantage of the second way is that it actually updates the DOM properly in all browsers so that you can actually read back and update the tags you added.

Using innerHTML does not update the DOM in all browsers and so the content added that way may not be able to be updated after it is added (if you need to do that).