A new document by document.write() is explicit but a new document by innerHTML is implicit, why?

On one side, If I open the browser console and execute document.write("Hi"); a new document will appear on the same browser window, so a new document was created with that language construct (whether if the previous document was deleted or whether if it still exists somewhere).

On the other side, if I open the browser console and execute:

newHTML = document.querySelector("body");
newHTML.innerHTML +=`
<div>Hi</div>
`;

a new document with that data will be created but it will be merged into the previous document so the end result would be that the previous document still appears generally regularly in the same browser window but just with the slight change (HTML being appended in this case) from the new document back to the that original one.
(a side effect of that strange merging would be defunctioning of all JavaScript in the original document).

A new document by document.write() is explicit but a new document by innerHTML is implicit, why?

This, i believe, is what you’re referring to.

Note that the addition assignment is still a reassignment – these two lines are equivalent:

document.body.innerHTML += '<div>foo</div>'
document.body.innerHTML = document.body.innerHTML + '<div>foo</div>'

So the documents are not really getting merged, even if there is some overlap in the markup. Instead,
a new document fragment is being created from parsing the markup of the document body + the added HTML string; and the body’s previous children are then getting replaced with the contents of that fragment. Have a look at the specs for the gory details. :-)

Yeah, so if anything, document.write() would clear the document implicitly.

I thanks,
I didn’t find in the linked pages in your reply the word “stream”.

If indeed document.write() writes to a new document than I wonder why do we need the word “stream” at all.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.