fly.bird
fly.bird

Reputation: 131

Getting element name inside html using cheerio

New to front end stuff. I am having trouble getting element inside html using cheerio. Please see below what I am trying. I looked other posts, they help to understand how cheerio works but not this.

My goal is to get value ex. I want to get value 67% from <td class="ctr2">67%</td>. I am getting undefined. This tag td class="ctr2" appears multiple times but I want from first only.

I have been trying for quiet some time now. I get undefined using cheerio. What is that I am missing?

<tfoot>
                <tr>
                    <td>Total</td>
                    <td class="bar">966 of 2,945</td>
                    <td class="ctr2">67%</td>
                    <td class="bar">56 of 168</td>
                    <td class="ctr2">66%</td>
                    <td class="ctr1">72</td>
                    <td class="ctr2">224</td>
                    <td class="ctr1">167</td>
                    <td class="ctr2">580</td>
                    <td class="ctr1">31</td>
                    <td class="ctr2">140</td>
                    <td class="ctr1">0</td>
                    <td class="ctr2">17</td>
                </tr>
            </tfoot>



I am trying below using cheerio in node.js

const cheerio = require('cheerio');
var fs = require('fs');

const demo= cheerio.load(fs.readFileSync('sample123.html'))
console.log(demo('#ctr2'));

Upvotes: 0

Views: 664

Answers (1)

jfriend00
jfriend00

Reputation: 707148

I see a couple problems with your code:

  1. #ctr2 is a selector for an element with id="cntr2". You don't have any id values in your HTML. Instead, you need to use ".ctr2" if you want to select items with that class name.
  2. Your HTML is incomplete as there is no <table> and </table> surrounding it.

If you fix those two things and run this code:

const cheerio = require('cheerio');
var fs = require('fs');

const $ = cheerio.load(fs.readFileSync('sample123.html'))
$('.ctr2').each((index, element) => {
    console.log($(element).text());    
});

Then, it will generate this output:

67%
66%
224
580
140
17

If you only want the first .cntr2 item, you can use .first() on the selector results like this:

const cheerio = require('cheerio');
var fs = require('fs');

const $ = cheerio.load(fs.readFileSync('sample123.html'))
console.log($('.ctr2').first().text());

Which will generate this output:

67%

Upvotes: 1

Related Questions