javascript,如何删除< html>< head>< body>将DOMparser与text / html一起使用时的元素 [英] javascript, how to remove the <html><head><body> elements when using DOMparser with text/html
本文介绍了javascript,如何删除< html>< head>< body>将DOMparser与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文档,这是包括
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>
如果我只想要< div id = hi> ; fe< / div>< div id = h2> fe< / div>< div id = hj> fe< / div>
部分?我该怎么办?
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
*如果希望,如果parentNode < div id = parent>
*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>
但是我得到了
<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"));
更新
或 innerHTML
console.log(temp_node.querySelector("body").innerHTML);
这篇关于javascript,如何删除< html>< head>< body>将DOMparser与text / html一起使用时的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文