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 = '<h1>Hello World</h1><h2>Lorem ipsum</h2>';
const myHtmlElement = new DOMParser().parseFromString(myHtmlString,
'text/html').body.children;
const myElement = document.querySelector('header');
myElement.append(...myHtmlElement);
Note use of spread operator with append. Unlike appendChild() method, append() method allows inserting multiple nodes.