Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
document.open() and the DOM tree of the loaded (closed) browser window on which it works
If I execute in browser console:
document.write("Hello");
A new DOM document with the text Hello appears in the same browser window.
From MDN documentation:
Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document.
What is the meaning of "clear" here?
Does it mean "totally deleted" or is the previous DOM tree stored somewhere and can be retrieved?
1 answer
At the documetation you linked, if you click on "which will clear the document", it'll go to the documentation for document.open
, and that page says in the beginning:
All existing nodes are removed from the document.
And once removed, you can't retrieve them.
Making a test in this page, this prints a NodeList
with lots of elements:
console.log(document.body.childNodes);
But after doing document.write('abc')
, the document.body.childNodes
will have only one element, which is the text node containing "abc".
All the original document's child nodes were lost and can't be retrieved from the document anymore.
A way to avoid losing the original DOM tree is to make a copy of the document before deleting it:
// copy document
var originalDocument = document.cloneNode(true);
// this removes all document's nodes
document.write('abc');
// but you can restore the original document (not sure if everything will work, such as scripts and event handlers)
document.documentElement.replaceChildren(originalDocument.documentElement);
By using cloneNode(true)
, I create a deep copy of the entire document (true
indicates that I want to clone not only the document
, but also all its descendants). So I'll have an entire copy of the DOM tree.
In the example above I show how to restore the original document (but I'm not sure if all JavaScript and event handlers will be kept and work properly). But you can actually do anything you want with it (such as use originalDocument.querySelector
to search for a specific node, access originalDocument.body
, etc).
0 comment threads