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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With