Just wanted to second rnd_me:
Though the code I posted is strictly speaking XHTML compliant, when running large loops, it is enormously slower (especially on IE).
Personally I only use createElement and appendChild for table creation. For obvious reasons, a table created dynamically should be created/edited in such a way as to maintain strict XML standards, if only for data capture/migration. And I never use createTextNode (there really is no reason not to just use innerHTML instead).
In all other cases (non-tables) I will always have the general element structure already created server-side (for example, I'd already have the h1 and p tags organized/styled) and use innerHTML to change the content. There really are few cases where it's best to use client-side script to
add (as opposed to
manipulate) major content - it's impossible to SEO and not part of your initial DOM.
EDIT: I may have to take back what I said about speed. I ran some numbers and this is what I found.
For these two functions in question:
Code:
function func1()
{
var doc_body = document.getElementById("place");
var article_header = document.createElement("h1");
article_header.appendChild(document.createTextNode("Article Title"));
var article_body = document.createElement("p");
article_body.appendChild(document.createTextNode("I have so much to tell you about this topic I don\'t know where to begin..."));
doc_body.appendChild(article_header);
doc_body.appendChild(article_body);
}
function func2()
{
var doc_body = document.getElementById("place");
doc_body.innerHTML = "<h1>Article Title</h1><p>I have so much to tell you about this topic I don\'t know where to begin...</p>";
}
They performed at identical speeds up until iteration 500. It wasn't until around 650 iterations that func2 began to perform noticeably better, and even then it was a small difference.
Now, when you change "innerHTML =" to "innerHTML +=", func2 is
always slower (for obvious reasons). Now most of the time, a smart programmer won't mess with innerHTML until he has compiled his entire insertion into a single string. Still, this goes to show that DOM methods aren't always that much slower - something I wasn't aware of before tonight.