简体   繁体   中英

Get comment nodes in DOM deep level

How can I get an array or array-like (JQuery object) containing all the comment elements in the DOM? JQuery contents() only retrieve 1 level elements.

The broader problem: I need to remove all the elements between 2 text comments in my DOM. Comments can also be in child elements.

...html code...
<!--remove from here-->
...code...
<!--finish removing-->
...html code...

So after the method, HTML DOM should look like:

...html code...
...html code...

Thanks.

You can use TreeWalker with whatToShow set to NodeFilter.SHOW_ALL to see all nodes on your document.

 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); } 
 <!--Folowing element will be deleted--> <span> Hello world</span> <!-- the next one should be kept --> <span> keep me !</span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM