How to add body element to empty DOM document?

I have this line that represents the body of the page that I would like to parse for some elements. I believe (feel free to contradict me), the best way to do this is to create an empty document, then add a body and use standard JS methods to get what I want.
But I don't seem to be able to add a body to the document. In chrome, the following code does not work on line 2 with NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7 .

  var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null); dom.firstChild.innerHTML = "<body><p>Hello world</p></body>"; 

Is there any way to achieve what I want?

+8
javascript dom
source share
3 answers

It is not possible to edit the innerHTML of the root element of a document, but it is possible for a child node. So this works:

  var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null); var body = dom.createElement("body"); body.innerHTML = "<p>hello world</p>"; dom.firstChild.appendChild(body); 
0
source share

Since we are several years further than the originally accepted answer, I would like to give a more modern one.

In Firefox 50.0.2 you can do this:

 document.body = document.createElement("body"); document.body.innerHTML = "<p>Hello World!</p>"; 

Here the body is created and directly attached to "document.body". Some reading ( https://html.spec.whatwg.org/multipage/dom.html#the-body-element-2 ) made me realize that the document attribute "body" can be either "null" or contain an object of type "body" or (not recommended) "frameset".

The following shows if it doesn’t work , i.e. creates a blank page because the purpose of "document.body" is missing:

 var body = document.createElement("body"); body.innerHTML = "<p>Hello World!</p>"; 

Instead of document.body = body; you can do this: document.documentElement.appendChild(body); whereas document.firstChild.appendChild(body); throws an error ("HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy").

One could argue whether adding a paragraph by evaluating innerHTML is a better way, but that's a different story.

+5
source share

In recent versions of chrome, I noticed that Antoine’s answer doesn’t work - you get a blank page. This, however, works in chrome:

 var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null); var body = dom.createElement("body"); dom.documentElement.appendChild(body); // set timeout is needed because document.body is created after the current continuation finishes setTimeout(function() { document.body.innerHTML = "Hi" },0) 
+1
source share

All Articles