Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 938
GWorking Avatar asked Mar 15 '23 22:03

GWorking


1 Answers

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

like image 185
davcs86 Avatar answered Apr 06 '23 02:04

davcs86