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
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
Most helpful comment
$.root().find('*').contents()seems to work. (I'm not sure about the performance though)