How can I convert an HTML string to a DOM element in JavaScript?
Rashid D
rashid d profile pic

To convert an HTML string to a DOM element in JavaScript, you can use theDOMParser API or create an empty element and set itsinnerHTML property. Here's a step-by-step approach for both methods: 1. UsingDOMParser: - TheDOMParser API allows you to parse an HTML string and create a DOM document from it.

1
2
3
4
5
6
7

   function htmlToElement(html) {
     const parser = new DOMParser();
     const doc = parser.parseFromString(html, 'text/html');
     return doc.body.firstChild;
   }
   

In this example, thehtmlToElement function takes anhtml string parameter. It creates a newDOMParser instance and uses theparseFromString() method to parse the HTML string and obtain aDocument object. The'text/html' parameter specifies that the input string is an HTML document. Finally, it returns the first child element of thebody of the parsed document. 2. UsinginnerHTML: - Alternatively, you can create an empty element, set itsinnerHTML property to the HTML string, and retrieve the resulting element.

1
2
3
4
5
6
7

   function htmlToElement(html) {
     const wrapper = document.createElement('div');
     wrapper.innerHTML = html;
     return wrapper.firstChild;
   }
   

In this approach, thehtmlToElement function takes anhtml string parameter. It creates a new

element usingdocument.createElement(). Then, it sets theinnerHTML property of thediv to the HTML string. Finally, it returns the first child element of thediv. Here's an example usage of thehtmlToElement function:

1
2
3
4
5

const htmlString = '<div><h1>Title</h1><p>Paragraph</p></div>';

const element = htmlToElement(htmlString);
console.log(element); // Output: <div>...</div>

In this example, thehtmlToElement function is called with an HTML string. It converts the HTML string into a DOM element and assigns it to theelement variable. The resultingelement represents the top-level element of the parsed HTML string. Note that the resulting DOM element can be appended to the document or manipulated further as needed. Additionally, ensure that the HTML string is well-formed to avoid unexpected parsing errors.