0

New to javascript, apology if this is a dumb question. The two statement in the title seems to be doing the same thing, are there any particular difference that I need to be aware of?

Oscar LT
  • 737
  • 1
  • 4
  • 21
Sunny Chu
  • 57
  • 5
  • 1
    They do not do the same thing. http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – epascarello Mar 22 '16 at 17:01
  • 2
    https://developer.mozilla.org/en-US/docs/Web/API/Document/write and https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML – j08691 Mar 22 '16 at 17:01

2 Answers2

4

They do not do the same thing. document.write will just append to the page as its loading, wherever in the page the <script> tag happens to be. If you call document.write after the page is loaded, it will erase the entire page before appending.

On the other hand, document.getElementById("").innerHTML = '' replaces the HTML of a certain element with what you give it (you can also append with .innerHTML += '').

It's highly suggested not to use document.write in your page.

Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
3

document.write can be used to emit markup during the parsing of the page. It cannot be used for modifying the page after it's parsed. The output of document.write goes straight into the parser as though it had been in the HTML document in the first place

innerHTML, which is not a function but rather a property, exists on all DOM element instances, and can be used to set their content, using markup. This, along with the various DOM methods available on instances, is the primary way that dynamic web pages are done.

Oscar LT
  • 737
  • 1
  • 4
  • 21