javascripthtmldom

Converting HTML string into DOM elements?


Is there a way to convert HTML like:

<div>
<a href="#"></a>
<span></span>
</div>

or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().

Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.


Solution

  • You can use a DOMParser, like so:

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