Converting HTML string to DOM element(s)

If you have some markup as string and wish to add it to a HTML page via JavaScript, the old way was to use innerHTML property like this:

const myHtmlString = '<h1>Hello World</h1>';
const myElement = document.querySelector('header');
myElement.innerHTML = myHtmlString;

However this replaces the whole content of element with new HTML string which may not always be desirable. Often you just want to add the new HTML as a child to an element in your page. In such cases you can use DOMParser interface like this:

const myHtmlString =
    `<div>
        <h1>Hello World</h1>
        <h2>Lorem ipsum</h2>
        <p>My first paragraph</p>
    </div>`;
const myHtmlElement: HTMLCollection = new DOMParser()
    .parseFromString(myHtmlString, 'text/html').body.children;
const body = document.querySelector('body')!;
body.append(...myHtmlElement);

Note use of spread operator with HTMLCollection. You need spread operator before using append() or appendChild() to add elements in HTMLCollection to the DOM.

If you need to find an element in HTMLCollection you need to iterate it like this:

Array.from(myHtmlElement).forEach(element => {
  console.log(element);
});