I want to create new DOM elements in a blank document which has no structure whatsoever (no root node either, I suppose). Basically like opening a new tab in the browser and creating its DOM from zero. Is this possible?
I've been searching through all the answers here and I've tried all the methods used in the past by others who asked similar questions. For example, I tried using:
var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
var body = dom.createElement("body");
body.innerHTML = "<p>GG WP</p>";
dom.firstChild.appendChild(body);
It didn't work. Next, I've tried using this:
var doc = document.implementation.createHTMLDocument("New Document");
var p = doc.createElement("p");
p.innerHTML = "Javascript is easy, but I still suck at it";
Didn't work either. So, I tried using a DOMParser:
var parser = new DOMParser();
var doc = parser.parseFromString("<body>It still doesn't work.</body>", "text/html");
Note: I am looking for a method which creates DOM elements in an empty document which are rendered (preferrably in the current tab). Because everyone may have different new tab settings, the way I tested all the solutions was by opening a new tab and executing
document.write();
first, just to make sure the current tab document has no DOM structure whatsoever.
UPDATE: I found the answer in the link posted by Mehdi (What other options for replacing entire HTML document via W3C DOM?). This works:
document.open();
document.write('<html><body></body></html>');
document.close();