JavaScript Parse and Convert Raw HTML String to DOM Nodes
Let’s say we have an HTML string like the following that we just want to convert into pure DOM nodes:
const htmlString = `
<div id="root">
<h1>Hello</h1>
<p>World</p>
</div>
`;
What are our options ? Let’s quickly go through all of them.
Range API
The Range API provides us with a method called createContextualFragment
that we can use to generate a DocumentFragment containing the parsed DOM nodes out of the passed HTML string.
const range = document.createRange();
const fragment = range.createContextualFragment(htmlString);
Template
We can create a template
tag element in memory and then pass the HTML string to it’s innerHTML
property. Effectively the template.content
property will end up having the DOM nodes wrapped in a DocumentFragment.
const template = document.createElement('template');
template.innerHTML = htmlString;
const fragment = template.content;
DOMParser
Using the DOMParser.parseFromString()
method, we can parse and convert an HTML or XML string into DOM nodes wrapped in an HTMLDocument
(or XMLDocument
).
const parser = new DOMParser();
// HTMLDocument(<html><body>...parsed nodes</body></html>)
const doc = parser.parseFromString(htmlString);
// Parsed nodes
const nodes = doc.body;
If you want to learn about how to render raw HTML strings into a target DOM node, then I’ve written about it here.