Cheerio: Removing Comments

Created on 23 May 2013  路  7Comments  路  Source: cheeriojs/cheerio

I'd like to use cheerio to remove comments in my html -
before, I get stuck in, is there an already prescribed way to di this?

thanks

Most helpful comment

$.root().find('*').contents() seems to work. (I'm not sure about the performance though)

All 7 comments

What you can do is filter on comment nodes and remove them.

function isComment(index, node) {
  return node.type === 'comment'
}
$.root().contents().filter(isComment).remove();
$('head').contents().filter(isComment).remove();
$('body').contents().filter(isComment).remove();

This doesn't seem to actually work?
Calling $.root().html() after that still returns the comments.

How do I get the html with the html comments removed?

@azakus's solution works for me:

var $ = cheerio.load('<!-- foo --> bar <!-- baz -->');

$.root()
.contents()
.filter(function() { return this.type === 'comment'; })
.remove();

$.root().html();  // => ' bar '

@davidchambers You're right, your example works, I'll try to debug why mine doesn't (probably my fault).

@davidchambers I see, change your html to: <div><!-- foo --> bar <!-- baz --></div>
It doesn't check in any nested elements

$.root().find('*').contents() seems to work. (I'm not sure about the performance though)

cheers

Was this page helpful?
0 / 5 - 0 ratings

Related issues

unicrus picture unicrus  路  4Comments

miguelmota picture miguelmota  路  3Comments

becush picture becush  路  3Comments

clayrisser picture clayrisser  路  4Comments

robogeek picture robogeek  路  4Comments