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

1) document.write() puts the contents directly to the browser where the user can see it.

this method writes HTML expressions or JavaScript code to a document.

The below example will just print ‘Hello World’ into the document

<html>
  <body>
    <script>
    document.write("Hello World!");
    </script>
  </body>
</html>

2) document.innerHTML changes the inner content of an element

It changes the existing content of an element

The below code will change the content of p tag

<html>
<body>
<p id="test" onclick="myFun()">Click me to change my HTML content or my inner HTML</p>
<script>
function myFun() {
  document.getElementById("test").innerHTML = "I'm replaced by exiesting element";
}
</script>
</body>
</html> 

you could use document.write() without any connected HTML, but if you already have HTML that you want to change, then document.innerHTML would be the obvious choice.


innerHTML and document.write are not really comparable methods to dynamically change/insert content, since their usage is different and for different purposes.

document.write should be tied to specific use cases. When a page has been loaded and the DOM is ready you cannot use that method anymore. That's why is generally most used in conditional statements in which you can use it to syncronously load external javascript file (javascript libraries), including <script> blocks (e.g. when you load jQuery from the CDN in HTML5 Boilerplate).

What you read about this method and XHTML is true when the page is served along with the application/xhtml+xml mime type: From w3.org

document.write (like document.writeln) does not work in XHTML documents (you'll get a "Operation is not supported" (NS_ERROR_DOM_NOT_SUPPORTED_ERR) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type

Another difference between these approaches is related on insertion node: when you use .innerHTML method you can choose where to append the content, while using document.write the insertion node is always the part of document in which this method was used.


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.

Tags:

Javascript