javascript,如何在将 DOMparser 与 text/html 一起使用时删除 元素

2024-01-09

The code

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>

Use childNodes

console.log(temp_node.childNodes[1].childNodes[0]);

or querySelector

console.log(temp_node.querySelector("#hi"));

JSFiddle 演示 http://jsfiddle.net/davcs86/m4thydjd/

Update

or innerHTML

console.log(temp_node.querySelector("body").innerHTML);

JSFiddle 演示 http://jsfiddle.net/davcs86/m4thydjd/1/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

javascript,如何在将 DOMparser 与 text/html 一起使用时删除 元素 的相关文章

随机推荐