user1931754
user1931754

Reputation:

Document object write method

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.

Upvotes: 0

Views: 63

Answers (1)

Joseph
Joseph

Reputation: 119837

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.

Upvotes: 7

Related Questions