gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:23:38 27 4
gpt4 key购买 nike

代码

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>

最佳答案

使用childNodes

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

querySelector

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

JSFiddle demo

更新

innerHTML

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

JSFiddle demo

关于javascript,如何在将 DOMparser 与 text/html 一起使用时删除 <html><head><body> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32280798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com