Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text in parent without children using cheerio

I am trying to extract just the content of a div - without any of the children of that div - using cheerio. If I just use div.text() - I get all the text - parent and children. Here's the HTML - I just want the value "5.25"

The code below currently returns "Purchase price $5.25"

The HTML below:

<div class="outer tile"> 
    < ... various other html here > 
    <div class="cost">
        <span class="text">Purchase price </span>
        <small>$</small>5.25
    </div>
</div>

with the extract of the relevant node.js CHEERIO code below:

var $ = cheerio.load(data);
$("div.outer.tile").each(function(i, e) {
  var price = $(e).find('div.price');
      console.log(price.text());
});
like image 434
GadgetGuy Avatar asked Dec 30 '13 03:12

GadgetGuy


2 Answers

Anyone still wondering how to do this in Cheerio:

$('div.classname').first().contents().filter(function() {
    return this.type === 'text';
}).text();
like image 150
Evers Avatar answered Oct 16 '22 18:10

Evers


i like this most:

$('div.cost').children().remove().end().text();

which i find more concise (no idea about efficency).

source

runkit

like image 38
fffact Avatar answered Oct 16 '22 17:10

fffact