How to get the text

Viewed 124

I have some html to scrape.

<div class="content">
  <strong> This is first content </strong> This is second content
  <br />
  <small>
    <p>Something</p>
  </small>
</div>

how to get the This is second content with cheerio ?

5 Answers

Using nodeType property, it could solve your problem even if you have text before <strong> tag

<div class="content">
  Before first content
  <strong> This is first content </strong> This is second content
  <br />
  <small>
    <p>Something</p>
  </small>
</div>

Then it could be

var cheerio = require("cheerio")
const $ = cheerio.load('<div class="content">Before first content<strong> This is first content </strong> This is second content<br /><small><p>Something</p></small></div>');

var $outer = $("div.content").contents().filter(function() {
    return this.nodeType === 3;
});

console.log($outer.text()); //"Before first content This is second content"

$outer.each(function() {
    console.log($(this).text());
});
//"Before first content"
//" This is second content"

Check it here

You can't directly select text nodes. I usually do something like:

$('.content strong')[0].nextSibling.data

Maybe this could help:

<div class="content">
  <strong> This is first content </strong> <span class="toBeSelected">This is second content</span>
  <br />
  <small>
    <p>Something</p>
  </small>
</div>

After this you can select the text this way.

$('div .toBeSelected').html()

Ideally you should put the 'This is a second content' in span or something else to specify properly to get its content.

do this:

<div class="content">
 <strong>This is first content</strong><span>This is second content</span>
<br>
  <small>
    <p>Something</p>
  </small>
</div>

Get it like this

console.log($('.content :nth-child(2)').text())

Working Demo: https://jsfiddle.net/usmanmunir/vg1dqm3L/17/ for you.

I think you can use regex to get the second content.

    const cheerio = require('cheerio');
    const $ = cheerio.load(`<div class="content">
    <strong> This is first content </strong> This is second content

    <br />
    <small>
    <p> Something </p>
    </small>
    </div>
    `);
    console.log($('div').html().replace(/\n/g, '').match(/<\/strong>(.*)<br>/)[1])
Related