Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

javascript - 将HTML字符串转换为DOM元素? [重复](Converting HTML string into DOM elements? [duplicate])

This question already has an answer here:(这个问题在这里已有答案:)

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype 22 answers(使用内置DOM方法或Prototype 22答案 从HTML字符串创建新的DOM元素)

Is there a way to convert HTML like:(有没有办法转换HTML像:)

<div> <a href="#"></a> <span></span> </div> or any other HTML string into DOM element?(或任何其他HTML字符串到DOM元素?) (So that I could use appendChild()).((这样我就可以使用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().(我知道我可以做.innerHTML和.innerText,但这不是我想要的 - 我真的希望能够将动态HTML字符串转换为DOM元素,以便我可以在.appendChild()中传递它。) Update: There seems to be confusion.(更新:似乎有困惑。) I have the HTML contents in a string, as a value of a variable in JavaScript.(我有一个字符串中的HTML内容,作为JavaScript中变量的值。) There is no HTML content in the document.(文档中没有HTML内容。)   ask by Tower translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a DOMParser , like so:(您可以使用DOMParser ,如下所示:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...