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
.