How to Create a New DOM Element from HTML String

HTML5 introduced the <template> element which can be used for creating a DOM element from HTML string.

Javascript create a new DOM element from HTML string
function htmlToElem(html) { let temp = document.createElement('template'); html = html.trim(); // Never return a space text node as a result temp.innerHTML = html; return temp.content.firstChild; } let td = htmlToElem('<td>foo</td>'), div = htmlToElem('<div><span>nested</span> <span>stuff</span></div>'); alert(td); alert(div); /* @param {String} HTML representing any number of sibling elements @return {NodeList} */ function htmlToElems(html) { let temp = document.createElement('template'); temp.innerHTML = html; return temp.content.childNodes; } let rows = htmlToElems('<tr><td>foo</td></tr><tr><td>bar</td></tr>'); alert(rows);

The <template> element is supported in all major browsers.

Note that HTML has restrictions on what element types you can use inside element types; for example, <td> cannot be put as a direct child of a <div> element. This causes the elements to vanish. The <template> element has no such restrictions on its content.

The <template>Tag

The <template> tag stores HTML code fragments that can be cloned and inserted in an HTML document. The <template> element is represented in DOM as a HTMLTemplateElement that has the .content property of DocumentFragment type so as to provide access to the contents of the template. This allows to convert an HTML string to DOM elements by setting the innerHTML of a <template> element, then reach into the .content property.