Say you have some HTML that is a string:
let string_of_html = `

Cool

`;
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:



text inside node



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