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

倖福魔咒の 提交于 2019-12-23 12:34:30

问题


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)

This code results in the full html document, this is including

<html><head></head><body>
<div id="hi">fe</div>
<div id="h2">fe</div>
<div id="hj">fe</div>
</body></html>

What if I want only the <div id="hi">fe</div><div id="h2">fe</div><div id="hj">fe</div> part? How can I do it?

And, if I want to append all nodes, is there a way to do it without a loop?

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

*What I'd wish, if parentNode is <div id="parent">

<div id="parent">
 <div id="hi">fe</div>
 <div id="h2">fe</div>
 <div id="hj">fe</div>
</div>

But I get

<div id="parent">
 <body>
  <div id="hi">fe</div>
  <div id="h2">fe</div>
  <div id="hj">fe</div>
 </body>
</div>

回答1:


Use childNodes

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

or querySelector

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

JSFiddle demo

Update

or innerHTML

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

JSFiddle demo




回答2:


The property documentElement returns the following:

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

There are other properties that exist on the Document, .body is one of which. Using .body (instead of querySelector) will give you fast direct access to the body of your HTML content, which you can then use .innerHTML on to get its inner contents:

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

See working example:

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


来源:https://stackoverflow.com/questions/32280798/javascript-how-to-remove-the-htmlheadbody-elements-when-using-domparser-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!