Get text in parent without children using cheerio

徘徊边缘 提交于 2019-12-01 15:00:52

问题


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());
});

回答1:


Anyone still wondering how to do this in Cheerio:

$('div.classname').first().contents().filter(function() {
    return this.type === 'text';
}).text();



回答2:


i like this most:

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

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

source

runkit




回答3:


I used this post

Get the text after span element using jquery

as reference to make a fiddle

http://jsfiddle.net/TKwhY/

It was new to me, but you can get text nodes by returning only elements of nodeType 3

var a = $('.cost').first().contents().filter(function() {
    return this.nodeType == 3;
});


来源:https://stackoverflow.com/questions/20832910/get-text-in-parent-without-children-using-cheerio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!