Create a DOM document from string, without JQuery

In case you're still looking for an anwer, and for anyone else coming accross it, I just have been trying to do the same thing myself. It seems you want to be looking at javascript's DOMImplementation:

http://reference.sitepoint.com/javascript/DOMImplementation

There are few references to compatibility as well here, but it's fairly well supported.

In essence, to create a new document to manipulate, you want to create a new Doctype object (if you're going to output some standards based stuff) and then create the new Document using the newly created Doctype variable.

There are multiple options to be put into both the doctype and the document, but if you're creating an HTML5 document, it seems you want to leave most of them as blank strings.

Example (New HTML5 DOM Document):

var doctype = document.implementation.createDocumentType( 'html', '', '');

var dom = document.implementation.createDocument('', 'html', doctype);

The new Document now looks like this:

<!DOCTYPE html>
<html>
</html>

Example (New XHTML DOM Document):

var doctype = document.implementation.createDocumentType(
    'html',
    '-//W3C//DTD XHTML 1.0 Strict//EN',
    'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
);

var dom = document.implementation.createDocument(
    'http://www.w3.org/1999/xhtml',
    'html',
    doctype
);

So it's up to you to populate the rest of it. You could do this as simply as changing

dom.documentElement.innerHTML = '<head></head><body></body>';

Or go with the more rigorous:

var head = dom.createElement( 'head' );
var body = dom.createElement( 'body' );
dom.documentElement.appendChild(head);
dom.documentElement.appendChild(body);

All yours.


https://developer.mozilla.org/en-US/docs/Web/API/DOMParser

var parser = new DOMParser();
var doc = parser.parseFromString("<html_string>", "text/html");

(the resulting doc variable is a documentFragment Object).