JavaScript Inject/Add or Append Raw Plain HTML Strings into DOM Nodes
So you want to either inject (add) or append raw HTML strings into the DOM directly or convert the HTML string into DOM nodes and then flush them ? Let’s see all the different ways to do them. We’ll assume that the following HTML string needs to be parsed and and added to the following node:
// HTML String
const htmlString = '<p>The Sky is Blue!</p>';
// DOM Element where the injection or append/prepend will happen
const root = document.querySelector('div#root');
Element.innerHTML
This is the most widely known approach I guess. The innerHTML
property on a DOM element allows getting and setting the entire HTML or XML markup (string) contained within. Setting it multiple times overrides the previous value and removes all the attached event listeners on the children.
root.innerHTML = htmlString;
Element.insertAdjacentHTML
The el.insertAdjacentHTML(pos, text)
method on a DOM element parses the input text as HTML or XML nodes and inserts the resulting nodes into the element at the specified pos
that can have the following values:
beforebegin
– Before the element, only valid if the element has a parent element.afterend
– After the element, only valid if the element has a parent element.afterbegin
– Inside the element, before its first child.beforeend
– Inside the element, after its last child.
Usage:
root.insertAdjacentHTML('beforeend', htmlString);
insertAdjacentHTML
is a slightly faster alternative to innerHTML
with the benefit of inserting/appending/prepending the HTML/XML markup instead of replacing/overriding the entire contents of the DOM element.
DOMParser
With the DOMParser.parseFromString(string, mimeType)
method we can convert a raw HTML string into DOM nodes first and then append or prepend the nodes into the target DOM element. Passing text/html
as the mimeType
invokes the HTML parser that’ll return an HTMLDocument
(with html
and body
tags). Let’s see the usage:
const xmlDoc = (new DOMParser()).parseFromString(htmlString, 'text/html')
// 1. The parsed nodes are in xmlDoc.body
// 2. The ... (spread) operator helps pass all children as arguments
root.append(...xmlDoc.body.children);
Feel free to use methods other than Element.append()
depending upon your needs:
Range
Using the Range API, we can create a DocumentFragment out of an HTML (or XML) string containing DOM nodes for all the tags and texts passed into the string.
const range = document.createRange();
const fragment = range.createContextualFragment(htmlString);
root.append(fragment);
Again, instead of append()
you could use the other options/methods listed in the DOMParser section above.
Note: Except this method (createContextualFragment()
), none of the other approaches in this article will execute any script
tags that are passed in the HTML string. Although with the other methods, there are still ways to execute JavaScript code passed within the string (more info here).
Template or DocumentFragment
We can create a template
element in memory and set its innerHTML
with the HTML string to create DOM nodes inside it. Then we can use the template.content
which is a DocumentFragment to append or prepend into any element in our DOM.
const template = document.createElement('template');
template.innerHTML = htmlString;
root.append(template.content);
TBH, we could do this by creating any other DOM element in memory and settings its innerHTML
, then pass the el.children
to the target node (like we did in the DOMParser
section above). Also this approach doesn’t seem much different from the innerHTML
section we saw above. But there’s one slight difference which could be important for some people – no context content restriction. Let me example.
If you did this:
const div = document.createElement('div');
div.innerHTML = '<td>Hello World</td>';
The td
will get stripped and only the text will get stored in the div
. It doesn’t matter whether you do it in memory (createElement
) or on a live DOM node. This is because a td
doesn’t belong to a div
contextually. You’ll face this contextual restriction with all the methods above. But if you want to get around it (for whatever reason), then template
will help you:
const t = document.createElement('template');
const d = document.createElement('div');
t.innerHTML = '<td>Hello World</td>';
d.append(t.content); // <div><td>Hello World</td></div>