I have a empty div identified by “parent”. I want to put an p element inside of it. There are two methods:
Firts method:
parent.innerHTML = "";
parent.innerHTML = "<p>My dummy text</p>";
Second method:
var myP = document.createElement('p');
var myText = document.createTextNode("My dummy text here");
myP.appendChild(myText);
parent.appendChild(myP);
Is there a difference between the two methods when it comes to the good practices?
Thanks!
When you’re intending to add plain text (no event listeners), no complex attribute values,
innerHTMLis usually a good option.If the text doesn’t contain any HTML tags,
textContentorinnerText(IE) is a better choice, because setting these properties won’t cause the string to be parsed as HTML.Tons of
document.createElementandappendChildare usually slower than setting theinnerHTMLproperty, especially when you’re comparing 1000x append-to-body vs 1x.innerHTML.It’s recommended to use
appendChildwhen you want to extend an element whose content is unknown (it may contain event listeners, or user-modified input elements).