Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Is there a general rule, when one should use document.write to change the website content and when to use .innerHTML?

So far my rules were:

1) Use document.write when adding new content

2) Use .innerHTML when changing existing content

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

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

like image 806
R_User Avatar asked Apr 10 '12 07:04

R_User


People also ask

What is the difference between document write and innerHTML?

document. write() puts the contents directly to the browser where the user can see it. document. innerHTML is changing the HTML of the object you apply it to.

Why do we use .innerHTML in JavaScript?

The innerHTML property can be used to write the dynamic html on the html document. It is used mostly in the web pages to generate the dynamic html such as registration form, comment form, links etc.

When we use document write in JavaScript?

write() writes to the document stream, calling document. write() on a closed (loaded) document automatically calls document. open() , which will clear the document.


1 Answers

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.

like image 82
Trevor Norris Avatar answered Sep 24 '22 23:09

Trevor Norris