【发布时间】:2015-11-23 16:34:38
【问题描述】:
代码
var txt = '<div id="hi">fe</div><div id="h2">fe</div><div id="hj">fe</div>'
var parser = new DOMParser();
var temp_node = parser.parseFromString(txt, "text/html").documentElement;
console.log(temp_node)
此代码生成完整的 html 文档,其中包括
<html><head></head><body>
<div id="hi">fe</div>
<div id="h2">fe</div>
<div id="hj">fe</div>
</body></html>
如果我只想要 <div id="hi">fe</div><div id="h2">fe</div><div id="hj">fe</div> 部分怎么办?我该怎么做?
而且,如果我想追加所有节点,有没有办法在没有循环的情况下做到这一点?
parentNode.appendChile(temp_node) // add the entire code
parentNode.appendChile(temp_node.firstElementChild.nextElementSibling) // add the parent <body> and the other layers inside
parentNode.appendChild(temp_node.firstElementChild.nextElementSibling.childNodes) // doesn't do the trick, it complains about not being a "node", I guess I'd need an "appendChilds" function that allows to add many nodes at once
*如果 parentNode 是 <div id="parent">,我想要什么
<div id="parent">
<div id="hi">fe</div>
<div id="h2">fe</div>
<div id="hj">fe</div>
</div>
但我明白了
<div id="parent">
<body>
<div id="hi">fe</div>
<div id="h2">fe</div>
<div id="hj">fe</div>
</body>
</div>
【问题讨论】:
标签: javascript html xml dom domparser