Fabian Tschullik
Fabian Tschullik

Reputation: 155

Cheerio get first element among multiple matches for class

I have this HTML:

<div class="flex__col--md-2 flex__col--xs-4  color-box color-box--orange color-box--no-pad  text-center">
                <p class="u-text-white">
                    <strong>
                        208,00 Euro
                    </strong>
                </p>
            </div>

The second part looks like this:

 <div class="flex__col--md-2 flex__col--xs-4  color-box color-box--orange color-box--no-pad  text-center">
                    <p class="u-text-white">
                        <strong>1.978,00 Euro</strong>
                    </p>
                </div>

The class "flex__col--md-2 flex__col--xs-4 col..." and the class "u-text-white" can be found twice in the html. I would like to slect the value from the first entry "208,00 Euro".

var parsedHTML = $.load(body);
console.log("the value");

Can someone help me to get the 208 euro to the console log using cheerio?

Upvotes: 0

Views: 7307

Answers (2)

ggorlen
ggorlen

Reputation: 56965

Improving on the existing answer, you can use natural CSS chaining without multiple .find() calls:

const cheerio = require("cheerio"); // ^1.0.0-rc.12

const html = `<div class="flex__col--md-2 flex__col--xs-4  color-box color-box--orange color-box--no-pad  text-center">
  <p class="u-text-white">
    <strong>208,00 Euro</strong>
  </p>
</div>
<div class="flex__col--md-2 flex__col--xs-4  color-box color-box--orange color-box--no-pad  text-center">
  <p class="u-text-white">
    <strong>1.978,00 Euro</strong>
  </p>
</div>`;

const $ = cheerio.load(html);
const text = $(".flex__col--md-2.flex__col--xs-4 p.u-text-white")
  .first()
  .text()
  .trim();
console.log(text); // => 208,00 Euro

The critical part of the answer here is .first(). .last() and .nth(0) are useful variant functions on .first().

Other options include:

const text = $(".flex__col--md-2.flex__col--xs-4 p.u-text-white:nth(0)")
  .text()
  .trim();

and

const text = $(".flex__col--md-2.flex__col--xs-4 p.u-text-white:first")
  .text()
  .trim();

Upvotes: 0

Arjun S Kumar
Arjun S Kumar

Reputation: 376

You should be able to access the data like this.

var firstEl = parsedHTML
  .find('.flex__col--md-2.flex__col--xs-4')
  .first()
  .find('.u-text-white');
var data = firstEl.find('strong').text();

Upvotes: 2

Related Questions