R_User R_User - 1 year ago 66
Javascript Question

When should one use .innerHTML and when document.write in JavaScript

Is there a general rule, when one should use

to change the website content and when to use

So far my rules were:

1) Use
when adding new content

2) Use
when changing existing content

But I got confused, since someone told me that on the one hand
is a strange Microsoft standard, but on the other hand I read that
is not allowed in XHTML.

Which structures should I use to manipulate my source code with JavaScript?

Answer Source

innerHTML can be used to change the contents of the DOM by string munging. So if you wanted to add a paragraph with some text at the end of a selected element you could so something like

document.getElementById( 'some-id' ).innerHTML += '<p>here is some text</p>'

Though I'd suggest using as much DOM manipulation specific API as possible (e.g. document.createElement, document.createDocumentFragment, <element>.appendChild, etc.). But that's just my preference.

The only time I've seen applicable use of document.write is in the HTML5 Boilerplate (look at how it checks if jQuery was loaded properly). Other than that, I would stay away from it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download