Fred J. Fred J. - 5 months ago 17
jQuery Question

get the comment element text using cherrio selector

This jQuery like selector "cheerio" tries to get the comments from the comments nodes in an html page.

$ is the cheerio object.
How can it do it? Thanks

console.log($('*').contents().length); //reports back more than 1000


$('*').contents().filter(function() {
if (this.nodeType == 8) {

//the following gives null for every node found
console.log($(this).html());

//the following gives blank for every node found
console.log($(this).text());
}
});

Answer

The content of a comment isn't either HTML (.innerHTML) or a value (.value), it's the .nodeValue. jQuery doesn't provide a function to get that for you and I doubt Cheerio does either, but you don't need one: Just use this.nodeValue:

$('*').contents().filter(function() {
  if (this.nodeType == 8) {
    console.log(this.nodeValue);
  }
});

(I've used filter there because your example did, but if you're not using the return value of filter, each makes more sense.)

Here's a DOM example, but presumabh Cheerio will work similarly:

$("*").contents().each(function() {
  if (this.nodeType === 8) {
    console.log(this.nodeValue);
  }
});
<!-- Comment 1 -->
<!-- Comment 2 -->
<!-- Comment 3 -->
<!-- Comment 4 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Comments