Antoine
Antoine

Reputation: 5245

How can I add a body element to an empty DOM document?

I have this string that represents the body of a page, which I would like to parse for some elements. I believe (feel free to contradict me) the best way to do so is to create an empty document, then add the body and use standard JS methods to get what I want.
But I don't seem to be able to add the body to the document. In chrome, the following code fails 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?

Upvotes: 16

Views: 23423

Answers (4)

Ketan Gupta
Ketan Gupta

Reputation: 1

We can simply write this code:

document.write('tagName Hello World tagName');

Upvotes: 0

JosefScript
JosefScript

Reputation: 600

As we are some 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 assigned to "document.body". Some reading (https://html.spec.whatwg.org/multipage/dom.html#the-body-element-2) made me understand, that the document's attribute "body" can either be "null" or contain an object of type "body" or (not recommended) "frameset".

The following does not work, i.e. produces a blank page, because the assignment to "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 might argue whether adding a paragraph by assessing innerHTML is the best way, but that's another story.

Upvotes: 14

B T
B T

Reputation: 60875

I noticed in recent versions of chrome, Antoine's answer doesn't work - you get a blank page. This, however, does work 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)

Upvotes: 3

Antoine
Antoine

Reputation: 5245

It's not possible to edit the innerHTML of the document's root element, but doing so of a child node is possible. 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);

Upvotes: 0

Related Questions