Forum Moderators: open

Message Too Old, No Replies

document.write vs document.body.appendChild

         

Skier88

12:56 am on Apr 14, 2010 (gmt 0)

10+ Year Member



This is not an issue since both methods work everywhere I've tested them, but I'm just wondering which method is better (more efficient, more compatible, etc) to use for creating a new element with js. Or, if one is the official/standard/preferred method, which it is.

eg: in my js powered slideshow, I create required elements with js so that it won't show up on browsers where it won't work. I could write:

document.write('<div id="r1"></div>');
var r1 = document.getElementById('r1');

or...

var r1 = document.createElement('div');
document.body.appendChild(r1);

Thanks for reading.

daveVk

3:59 am on Apr 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



document.write will not work as expected after the document has loaded, it overwrites the entire page at least in IE.

If this code is going into the body section, either will work the latter may not work with some old browsers, but is more versatile as you can append to any part of document.

Fotiman

1:37 pm on Apr 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In general, it's best to avoid document.write as it is very timing specific (as daveVk said, if you call it after the load event, it will overwrite the current document). Likewise, document.write does not encourage a clean separation of content and behavior.