views:

906

answers:

11

I see in some posts that people frown upon using document.write() in javascript when writing dynamic HTML.

Why is this? and what is the correct way?

+20  A: 

document.write() doesn't work with XHTML. It's executed after the page has finished loading and does nothing more than write out a string of HTML.

Since the actual in-memory representation of HTML is the DOM, the best way to update a given page is to manipulate the DOM directly.

The way you'd go about doing this would be to programmatically create your nodes and then attach them to an existing place in the DOM. For [purposes of a contrived] example, assuming that I've got a div element maintaining an ID attribute of "header," then I could introduce some dynamic text by doing this:

// create my text
var sHeader = document.createTextNode('Hello world!');

// create an element for the text and append it
var spanHeader = document.createElement('span');
spanHeader.appendChild(sHeader);

// grab a reference to the div header
var divHeader = document.getElementById('header');

// append the new element to the header
divHeader.appendChild(spanHeader);
Tom
It's actually executed when you call it. If you call it after the page has loaded it will overwrite the content.
Maiku Mori
Stick to HTML and `document.write` remains a useful tool.
Tim Down
+3  A: 

You can change the innerHTML or outerHTML of an element on the page instead.

iHunger
Preferably innerHTML, as outerHTML isn't widely supported.
bobince
A: 

The document.write method is very limited. You can only use it before the page has finished loading. You can't use it to update the contents of a loaded page.

What you probably want is innerHTML.

Mike Daniels
+2  A: 

I'm not particularly great at JavaScript or its best practices, but document.write() along with innerHtml() basically allows you to write out strings that may or may not be valid HTML; it's just characters. By using the DOM, you ensure proper, standards-compliant HTML that will keep your page from breaking via plainly bad HTML.

And, as Tom mentioned, JavaScript is done after the page is loaded; it'd probably be a better practice to have the initial setup for your page to be done via standard HTML (via .html files or whatever your server does [i.e. php]).

RoyalKnight
If you write dynamic components using javascript you will end up writing to DOM with javascript. While document.write() isn't really the way to go you will probably use innerHTML in most cases. Since innerHTML is a lot faster then using createNode/appendChild in all browsers. It's quite important when you have to generate a lot html/DOM elements. + it's document, not documment ;)
Maiku Mori
+6  A: 

document.write() will only work while the page is being originally parsed and the DOM is being created. Once the browser gets to the closing tag and the DOM is ready, you can't use document.write() anymore.

I wouldn't say using document.write() is correct or incorrect, it just depends on your situation. In some cases you just need to have document.write() to accomplish the task. Look at how google analytics gets injected into most websites.

After DOM ready, you have two ways to insert dynamic HTML (assuming we are going to insert new html into <div id="node-id"></div>):

1- using innerHTML on a node-

var node = document.getElementById('node-id');
node.innerHTML('<p>some dynamic html</p>');

2- using DOM methods-

var node = document.getElementById('node-id');
var newNode = document.createElement('p');
newNode.appendChild(document.createTextNode('some dynamic html'));
node.appendChild(newNode);

Using the DOM API methods might be the purist way to do stuff, but innerHTML has been proven to be much faster and is used under the hood in js libraries such as jQuery.

Ricky
You can use it, try it =). It's probably not what you want to do, but still you can.
Maiku Mori
A nice full answer, thankyou. I understand now that document.write() only is useful for when the page is loading and being created for the first time. For dynamically updating the page afterwards the DOM methods or innerHTML() are a must.
Gary Willoughby
Could you provide proof that innerHTML is always faster? I would doubt it's always the case. If you add nodes one at a time to an existing node in the DOM then I expect innerHTML is faster, since the browser potentially has to manipulate and re-render parts of the document at every stage, but if instead you create a new node tree and add its root node to the DOM at the end, I would expect that to be as fast or faster than using innerHTML.
Tim Down
@Maiku - LOL, true that :)@Tim - Here is a benchmark http://www.quirksmode.org/dom/innerhtml.htmlAnd actually, using document fragments seems to be the fastest : http://ejohn.org/blog/dom-documentfragments/
Ricky
@Ricky - thanks, interesting reading. Both linked articles are flawed: the quirksmode example is quite old, so is not tested against the most recent major version of any of the browsers and in IE's case the last two major versions (note that he tested against IE7 beta 3, not the final release). However, it does prove your point for IE6 and his example. John Resig's example, on the other hand, is extremely flawed and proves nothing, as the comments for the article show.
Tim Down
@Tim - This day in age, I think we should just trust the frameworks to do this low level DOM stuff for us. Hopefully, they know more than we do :)
Ricky
@Ricky - I've looked in depth at the code for some of these libraries and I wouldn't be so sure.
Tim Down
@Tim - ;-) .......
Ricky
+1  A: 

There are many ways to write html with JavaScript.

document.write is only useful when you want to write to page before it has actually loaded. If you use document.write() after the page has loaded (at onload event) it will create new page and overwrite the old content. Also it doesn't work with XML, that includes XHTML.

From other hand other methods can't be used before DOM has been created (page loaded), because they work directly with DOM.

These methods are:

  • node.innerHTML = "Whatever";
  • document.createElement('div'); and node.appendChild(), etc..

In most cases node.innerHTML is better since it's faster then DOM functions. Most of the time it also make code more readable and smaller.

Maiku Mori
A: 

I think you should use, instead of document.write, DOM javascript api like document.createElement, .createTextNode, .appendChild and similar. Safe and almost cross browser.

ihunger's outerHTML is not cross browser, IE only

Luca
+5  A: 
  1. DOM methods, as outlined by Tom.

  2. innerHTML, as mentioned by iHunger.

DOM methods are highly preferable to strings for setting attributes and content. If you ever find yourself writing innerHTML= '<a href="'+path+'">'+text+'</a>' you're actually creating new cross-site-scripting security holes on the client side, which is a bit sad if you've spent any time securing your server-side.

DOM methods are traditionally described as ‘slow’ compared to innerHTML. But this isn't really the whole story. What is slow is inserting a lot of child nodes:

 for (var i= 0; i<1000; i++)
     div.parentNode.insertBefore(document.createElement('div'), div);

This translates to a load of work for the DOM finding the right place in its nodelist to insert the element, moving the other child nodes up, inserting the new node, updating the pointers, and so on.

Setting an existing attribute's value, or a text node's data, on the other hand, is very fast; you just change a string pointer and that's it. This is going to be much faster than serialising the parent with innerHTML, changing it, and parsing it back in (and won't lose your unserialisable data like event handlers, JS references and form values).

There are techniques to do DOM manipulations without so much slow childNodes walking. In particular, be aware of the possibilities of cloneNode, and using DocumentFragment. But sometimes innerHTML really is quicker. You can still get the best of both worlds by using innerHTML to write your basic structure with placeholders for attribute values and text content, which you then fill in afterwards using DOM. This saves you having to write your own escapehtml() function to get around the escaping/security problems mentioned above.

bobince
A: 

Perhaps a good idea is to use jQuery in this case. It provides handy functionality and you can do things like this:

$('div').html('<b>Test</b>');

Take a look at http://docs.jquery.com/Attributes/html#val for more information.

Nyla Pareska
Why was this voted down?
Nyla Pareska
+1  A: 

Surely the best way is to avoid doing any heavy HTML creation in your JavaScript at all? The markup sent down from the server ought to contain the bulk of it, which you can then manipulate, using CSS rather than brute force removing/replacing elements, if at all possible.

This doesn't apply if you're doing something "clever" like emulating a widget system.

Rob
A: 

How to set properties of the newly added child node. For eg. in the mentioned illustration

var sHeader = document.createTextNode('Hello world!');

var spanHeader = document.createElement('span');

spanHeader.appendChild(sHeader);

document.body.appendChild(spanHeader);

How can we change the "style.display" of the newly added 'span' element? The approach :

spanHeader.style.display = 'none'

does not work. Neither the following code works :

var newEle = document.getElementById('spanHeader');

Aniket