Convert String to DOM Nodes

It wasn’t too long ago that browsers were mostly stagnant when it came to implementing new APIs and features, leading to the rise of MooTools (FTW), jQuery, Dojo Toolkit, Prototype, and likewise JavaScript toolkits. Then we started doing more client side rendering and were forced to use a variety of tricks to handle templates, including massive HTML strings in our JavaScript and even abusing tags to hold our templates.

Of course after you've placed your content into the template, you then need to turn that string into DOM nodes, and that process had a few of its own tricks, like creating an offscreen, dummy <div>, setting its innerHTML to the string value, grabbing the firstChild, and moving the node to its desired node. Each JavaScript toolkit would use its own strategy for converting string to DOM, highlighting the need for a standard method to accomplish this task.

Today we have a standard way for converting string to DOM with JavaScript: DOMParser.

The JavaScript

All you need to do is create a DOMParser instance and use its parseFromString method:

let doc = new DOMParser().parseFromString('
Hello!
', 'text/html');

Returned is a document containing the nodes generated from your string. With said document you can use standard node traversal methods to retrieve the nodes we specified in our string:

let doc = new DOMParser().parseFromString('
Hello!
', 'text/html'); let div = doc.body.firstChild; let divs = doc.body.querySelectorAll('div');

You don't need a single wrapping element like JSX components -- you can have sibling elements:

let doc = new DOMParser().parseFromString('
1
2
', 'text/html'); let firstDiv = doc.body.firstChild; let secondDiv = firstDiv.nextSibling;

Here's a simple wrapping function for DOMParser to retrieve the nodes:

let getNodes = str => new DOMParser().parseFromString(str, 'text/html').body.childNodes; let nodes = getNodes('
1
2
'); // [div, div]

The DOMParser object is an awesome, sane method for converting strings to DOM nodes within JavaScript. Ditch your old shims and switch to this efficient, simple API!

Related Post

Rojenx is a leading concept artist who work appears in games and publications

Check out his personal gallery here

In other news …