0

Document object write method works differently when used inside the function and when outside. When inside of function it replaces the entire elements on the document with the string specified in it but when outside the function, just below the element the content is written. Why do this happen?

function foo(){document.write("Maizere")}
element.onclick=foo

When the event occurs everything on the document is replaced with the string specified in the write method.

1
  • 1
    Don't use document.write(). Commented Jan 1, 2013 at 13:41

1 Answer 1

7

When the page (to be precise, document) is already loaded, document.write calls document.open before it writes which clears the current document first before writing. Thus, when placing document.write in a function which gets called after the page is loaded, the current page is cleared and the text in document.write takes its place.

However, when the page is still loading, document.write does not call document.open thus not clearing the page. Instead, it executes immediately and appends whatever it was assigned to write on the page.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.