This question might be stupid, or basic.
Can someone explain which is the best method in adding DOM elements. We have these two ways of adding DOM elements.
Scenario: Need to add <strong>Hi</strong>
inside an existing <div id="theEl"></div>
.
By editing the HTML inside them.
document.getElementById("theEl").innerHTML = '<strong>Hi</strong>';
By using
document.createElement()
.var hi = document.createTextNode("Hi"), strong = document.createElement("strong"); strong.appendChild(hi); mydiv = document.getElementById("theEl"); document.body.insertBefore(strong, mydiv);
Questions
- What is the best way to do? One is a single line, another is about five lines.
- What is the performance aspect?
- What is the right way or best practise?
- Is there any difference between the codes as a whole?
If at all this question is not making sense, please let me know, I will be glad to close this or even remove this. Thanks.
For the close voter, this is not going to be a duplicate of that question. One thing I just noted is, using createElement()
preserves the event handlers attached to the element. Even though that's a good point, any kind of basic web page, too has jQuery in them, which provides delegation and such stuff that allow me to have the event attached to the element even after change in HTML.
' + someDataFromUser + '
'`, you just opened up yourself to XSS attacks. – Brad Apr 12 '13 at 04:04