且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 HTML 字符串转换为 DOM 元素?

更新时间:2022-10-22 07:42:22

您可以使用 DOMParser,如下所示:

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="#">链接...console.log(doc.firstChild.firstChild.innerHTML);//=>链接

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.

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