是否有一种方法可以像这样转换HTML:

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

或任何其他HTML字符串到DOM元素?(这样我就可以使用appendChild())。我知道我可以做. innerhtml和. innertext,但这不是我想要的——我实际上希望能够将动态HTML字符串转换为DOM元素,以便我可以在. appendchild()中传递它。

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


当前回答

看看John Resig的纯JavaScript HTML解析器。

编辑:如果你想让浏览器为你解析HTML, innerHTML正是你想要的。从这个SO问题中:

var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;

其他回答

看看John Resig的纯JavaScript HTML解析器。

编辑:如果你想让浏览器为你解析HTML, innerHTML正是你想要的。从这个SO问题中:

var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;

好吧,在我思考了其他人的答案之后,我自己想到了答案。: P

var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);

你可以像这样使用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);=> 链接

或者,你也可以在html被转换为字符串时使用,

JSON.stringify()

稍后,当您想从HTML字符串中展开HTML时,使用

JSON.parse()

为什么不使用insertAdjacentHTML

例如:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here