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

javascript, how to remove the <html><head><body> elements when using DOMparser with text/html

密码

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

属性documentElementreturns如下:

Returns the Element that is a direct child of the document. For HTML documents, this is normally the HTMLHtmlElement object representing the document's <html> element.

- MDN

Document 上还存在其他属性,.body 就是其中之一。使用 .body(而不是 querySelector)可以让您快速直接访问 HTML 内容的 body,然后您可以使用 .innerHTML 获取其内容:

parser.parseFromString(txt, "text/html").body

查看工作示例:

const txt = '<div id="hi">fe</div><div id="h2">fe</div><div id="hj">fe</div>'
const parser = new DOMParser();
const temp_node = parser.parseFromString(txt, "text/html").body;
console.log(temp_node.innerHTML);