Categories
JavaScript Answers

How to convert HTML string into DOM elements with JavaScript?

Spread the love

To convert HTML string into DOM elements with JavaScript, we use the DOMParser constructor.

For instance, we write

const xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
const doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML);

to create a DOMParser object and call the parseFromString method with the xmLString and the MIME type.

Then we get the first child element’s HTML code with doc.firstChild.innerHTML.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *