mrgoos
mrgoos

Reputation: 1316

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.

Upvotes: 4

Views: 1270

Answers (1)

Kaiido
Kaiido

Reputation: 136736

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>

Upvotes: 6

Related Questions