mrg*_*oos 3 javascript jquery dom-manipulation
如何获得包含DOM中所有注释元素的数组或类似数组(JQuery对象)?
JQuery contents()只检索1个级别的元素.
更广泛的问题:我需要删除DOM中2个文本注释之间的所有元素.评论也可以在子元素中.
...html code...
<!--remove from here-->
...code...
<!--finish removing-->
...html code...
Run Code Online (Sandbox Code Playgroud)
因此,在该方法之后,HTML DOM应如下所示:
...html code...
...html code...
Run Code Online (Sandbox Code Playgroud)
谢谢.
您可以将TreeWalker与whatToShowset一起使用NodeFilter.SHOW_ALL以查看文档中的所有节点.
var treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ALL,
null,
false
);
var commentList = [];
while (treeWalker.nextNode()){
// keep only comments
if (treeWalker.currentNode.nodeType === 8)
commentList.push(treeWalker.currentNode);
}
var node;
while (node !== commentList[1]) {
node = commentList[0].nextSibling;
node.parentElement.removeChild(node);
}Run Code Online (Sandbox Code Playgroud)
<!--Folowing element will be deleted-->
<span> Hello world</span>
<!-- the next one should be kept -->
<span> keep me !</span>Run Code Online (Sandbox Code Playgroud)