Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  38] [ 6]  / answers: 1 / hits: 36678  / 12 Years ago, tue, april 10, 2012, 12:00:00

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?


More From » javascript

 Answers
28

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.


[#86342] Sunday, April 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kareem

Total Points: 733
Total Questions: 110
Total Answers: 102

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
kareem questions
Tue, Dec 7, 21, 00:00, 3 Years ago
Sat, May 15, 21, 00:00, 3 Years ago
Wed, Oct 7, 20, 00:00, 4 Years ago
;