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

问题描述:

有没有办法转换HTML,如:

Is there a way to convert HTML like:

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

或任何其他HTML字符串到DOM元素? (所以我可以使用appendChild())。我知道我可以做.innerHTML和.innerText,但这不是我想要的 - 我真的希望能够将动态HTML字符串转换为DOM元素,以便我可以在.appendChild()中传递它。

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().

更新:似乎有混乱。我有一个字符串中的HTML内容,作为JavaScript中变量的值。文件中没有HTML内容。

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.

您可以使用 DOMParser ,像这样:

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