Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery's answer below for details.

For older browsers, and node/jsdom: (which doesn't yet support <template> elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML):

function createElementFromHTML(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString.trim();

  // Change this to div.childNodes to support multiple top-level nodes.
  return div.firstChild;
}

Note that unlike HTML templates this won't work for some elements that cannot legally be children of a <div>, such as <td>s.

If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:

  • Prototype has this feature built-into its update() method.
  • jQuery has it implemented in its jQuery(html) and jQuery.parseHTML methods.
Answer from Crescent Fresh on Stack Overflow
Top answer
1 of 16
1127

Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery's answer below for details.

For older browsers, and node/jsdom: (which doesn't yet support <template> elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML):

function createElementFromHTML(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString.trim();

  // Change this to div.childNodes to support multiple top-level nodes.
  return div.firstChild;
}

Note that unlike HTML templates this won't work for some elements that cannot legally be children of a <div>, such as <td>s.

If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:

  • Prototype has this feature built-into its update() method.
  • jQuery has it implemented in its jQuery(html) and jQuery.parseHTML methods.
2 of 16
738

HTML 5 introduced the <template> element which can be used for this purpose (as now described in the WhatWG spec and MDN docs).

A <template> element is used to declare fragments of HTML that can be utilized in scripts. The element is represented in the DOM as a HTMLTemplateElement which has a .content property of DocumentFragment type, to provide access to the template's contents. This means that you can convert an HTML string to DOM elements by setting the innerHTML of a <template> element, then reaching into the template's .content property.

Examples:

/**
 * @param {String} HTML representing a single node (which might be an Element,
                   a text node, or a comment).
 * @return {Node}
 */
function htmlToNode(html) {
    const template = document.createElement('template');
    template.innerHTML = html;
    const nNodes = template.content.childNodes.length;
    if (nNodes !== 1) {
        throw new Error(
            `html parameter must represent a single node; got ${nNodes}. ` +
            'Note that leading or trailing spaces around an element in your ' +
            'HTML, like " <img/> ", get parsed as text nodes neighbouring ' +
            'the element; call .trim() on your input to avoid this.'
        );
    }
    return template.content.firstChild;
}

const td = htmlToNode('<td>foo</td>'),
      div = htmlToNode('<div><span>nested</span> <span>stuff</span></div>');

/**
 * @param {String} HTML representing any number of sibling nodes
 * @return {NodeList} 
 */
function htmlToNodes(html) {
    const template = document.createElement('template');
    template.innerHTML = html;
    return template.content.childNodes;
}

const rows = htmlToNodes('<tr><td>foo</td></tr><tr><td>bar</td></tr>');

Note that similar approaches that use a different container element such as a div don't quite work. HTML has restrictions on what element types are allowed to exist inside which other element types; for instance, you can't put a td as a direct child of a div. This causes these elements to vanish if you try to set the innerHTML of a div to contain them. Since <template>s have no such restrictions on their content, this shortcoming doesn't apply when using a template.

Using <template>s was previously not always possible due to Internet Explorer not supporting <template>s, but IE support is almost never a consideration nowadays and Can I Use characterises <template>s as "baseline" functionality "widely available across major browsers". Except in the rare few cases where you find yourself writing web content for dead browsers, this approach will now reliably work for you.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-create-an-element-from-a-string-in-javascript
Creating an element from a string in JavaScript - GeeksforGeeks
February 25, 2026 - Using innerHTML: Create a container element and set its innerHTML to the string, then access the created element. Using insertAdjacentHTML(): Directly inserts HTML string into the DOM at a specified position without overwriting existing content.
🌐
Go Make Things
gomakethings.com › converting-a-string-into-markup-with-vanilla-js
Converting a string into markup with vanilla JS | Go Make Things
August 13, 2019 - /** * Convert a template string ... goes here... }; The simplest way to do this is to create an element, insert the string into with innerHTML, then return the element....
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript string to html
How to Convert String to HTML in JavaScript | Delft Stack
February 2, 2024 - The JavaScript file defined a function called stringToHTML, which takes a string str as an argument. This function uses the DOMParser interface to parse the provided string as HTML.
🌐
CSS-Tricks
css-tricks.com › snippets › javascript › inject-html-from-a-string-of-html
Inject HTML From a String of HTML | CSS-Tricks
March 19, 2020 - 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;
🌐
Codegyan
codegyan.in › articles › how-to-convert-a-string-to-html-using-javascript.htm
How to Convert a String to HTML using JavaScript
December 30, 2021 - JavaScript, on the other hand, ... most straightforward method for converting a string to HTML is by leveraging the `innerHTML` property of an HTML element....
🌐
Daily Dev Tips
daily-dev-tips.com › posts › javascript-get-html-elements-from-a-string
JavaScript get HTML elements from a string
December 22, 2020 - To get started, let’s first define our HTML. We will be using a variable, which you can consider came from our CMS. const text = `<p>Some text</p><br /><a href="https://daily-dev-tips.com/">My website</a><hr /><a href="https://google.com">Another link</a>`; As you can see, we have two links in there. Let’s say we want to parse each link to add a target="_blank". We can leverage the DOMParser to convert this string into a dom element.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-create-an-element-from-a-string-in-javascript
How to create an element from a string in JavaScript ? | GeeksforGeeks
January 8, 2024 - The parseHTML() method of jQuery is used to parse an HTML string so that it can be used to create elements according to the given HTML.
🌐
W3docs
w3docs.com › javascript
How to Create a New DOM Element from HTML String | W3Docs
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.
🌐
David Walsh
davidwalsh.name › convert-html-stings-dom-nodes
Convert String to DOM Nodes
March 20, 2017 - The DOMParser API allows developers to create DOM nodes from and HTML string using JavaScript.
🌐
Medium
medium.com › @GemmaBlack › converting-a-string-into-html-dom-nodes-3b04d73e413c
Converting A String Into HTML Dom Nodes | by Gemma Black | Medium
January 25, 2018 - const cleanHTMLString = string => string .trim() .replace(/\r?\n|\r/g, "") // removes multiple lines .replace(/\s\s+/g, '') // removes extra white spaces
🌐
Quora
quora.com › What-is-the-process-for-converting-an-HTML-string-into-a-DOM-object-using-JavaScript
What is the process for converting an HTML string into a DOM object using JavaScript? - Quora
Answer: Assigning the HTML string directly to an Element.innerHTML is probably the easiest and the most optimal way of doing it as all the work is done by the browser. E.g. elem.innerHTML = ‘ this is hello world Once the above statement is executed, the HTML string will ...
🌐
DEV Community
dev.to › dailydevtips1 › javascript-get-html-elements-from-a-string-9dp
JavaScript get HTML elements from a string - DEV Community
December 22, 2020 - To get started, let's first define our HTML. We will be using a variable, which you can consider came from our CMS. const text = `<p>Some text</p><br /><a href="https://daily-dev-tips.com/">My website</a><hr /><a href="https://google.com">Another link</a>`; As you can see, we have two links in there. Let's say we want to parse each link to add a target="_blank". We can leverage the DOMParser to convert this string into a dom element.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Element › getHTML
Element: getHTML() method - Web APIs | MDN
3 weeks ago - An array of ShadowRoot objects to serialize. These are included regardless of whether they are marked as serializable, or if they are open or closed. The default value is an empty array. A string that represents the HTML serialization of the element.
🌐
SitePoint
sitepoint.com › javascript
Converting element object to HTML string? - JavaScript - SitePoint Forums | Web Development & Design Community
August 22, 2010 - after i’ve built an element, can i convert that element to html? the current method i’m thinking is to append this element to a new and call the Div’s innerHTML but it feels rather dirty. is there a better solution?