Inject HTML From a String of HTML

Avatar of Chris Coyier
Chris Coyier on

Say you have some HTML that is a string:

let string_of_html = `
  <div>Cool</div>
`;

Maybe it comes from an API or you’ve constructed it yourself from template literals or something.

You can use innerHTML to put that into an element, like:

document.body.innerHTML = string_of_html;

// Append it instead
document.body.innerHTML += string_of_html;

You have a bit more control if you go with the insertAdjacentHTML function as you can place the new HTML in four different places:

<!-- beforebegin -->
<node>
  <!-- afterbegin -->
  text inside node
  <!-- beforeend -->
</node>
<!-- afterend -->

You use it like…

el.insertAdjacentHTML('beforebegin', string_of_html);
el.insertAdjacentHTML('afterbegin', string_of_html);
el.insertAdjacentHTML('beforeend', string_of_html);
el.insertAdjacentHTML('afterend', string_of_html);

There are circumstances where you might want to have the newly-created DOM still in JavaScript before you do anything with it. In that case, you could parse your string first, like:

let dom = new DOMParser()
  .parseFromString(string_of_html, 'text/html');

That will give you a complete DOM, so you’ll then need to yank out the child you added. Assuming it has just one parent element, that’s like…

let dom = new DOMParser()
  .parseFromString(string_of_html, 'text/html');
let new_element = dom.body.firstElementChild;

Now you can mess around with that new_element as needed, I suppose before doing what you need to do with it.

It’s a bit more straightforward to do this though:

let new_element = document.createRange()
  .createContextualFragment(string_of_html);

You’ll get the element directly as a document fragment to append or whatever as needed. This method is notable in that it will actually execute <script>s it finds inside, which can be both useful and dangerous.

There is a considerable amount of nuance to all this. For example, the HTML needs to be valid. Malformed HTML just isn’t going to work. Malformed might also catch you by surprise, like putting a <tr> into a <table> will fail because it’s missing a <tbody>.

Koen Schaft write “Create a DOM node from an HTML string” that covers what we have here but in more detail and with more of the gotchas.