【问题标题】:javascript, how to remove the <html><head><body> elements when using DOMparser with text/htmljavascript,如何在将 DOMparser 与 text/html 一起使用时删除 <html><head><body> 元素
【发布时间】: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>

如果我只想要 &lt;div id="hi"&gt;fe&lt;/div&gt;&lt;div id="h2"&gt;fe&lt;/div&gt;&lt;div id="hj"&gt;fe&lt;/div&gt; 部分怎么办?我该怎么做?

而且,如果我想追加所有节点,有没有办法在没有循环的情况下做到这一点?

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 是 &lt;div id="parent"&gt;,我想要什么

<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


    【解决方案1】:

    documentElement 属性返回以下内容:

    返回作为文档的直接子元素的元素。对于 HTML 文档,这通常是 HTMLHtmlElement 对象表示 文档的 &lt;html&gt; 元素。

    -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);

    【讨论】:

      【解决方案2】:

      使用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

      【讨论】:

      • 如果我只有一个孩子,那就行了,但我确实有很多(问题已更新)。
      • 使用temp_node.querySelector("body").innerHTML
      • 是的,但是没有,因为我需要 DOM 结构。似乎使用 innerHTML 它丢失了(不是吗?)
      • 然后temp_node.childNodes[1].childNodes(无索引)
      • 是的,就是这样,我正在使用 createDocumentFragment 将所有 ChildNode 附加到父 div
      猜你喜欢
      • 2023-02-23
      • 1970-01-01
      • 2021-10-28
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      相关资源
      最近更新 更多