在没有孩子的家长中使用cheerio获取文本

我正在尝试使用cheerio来提取div的内容 – 没有该div的任何子项。 如果我只是使用div.text() – 我得到所有文本 – 父母和子女。 这里是HTML – 我只想要值“5.25”

下面的代码目前返回“购买价格$ 5.25”

下面的HTML:

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

与下面的相关node.js CHEERIO代码的摘录:

 var $ = cheerio.load(data); $("div.outer.tile").each(function(i, e) { var price = $(e).find('div.price'); console.log(price.text()); }); 

任何人仍然想知道如何在Cheerio做到这一点:

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

我最喜欢这个:

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

我发现更简洁(不知道效率)。

资源

runkit

我用这个post

使用jquery获取span元素之后的文本

作为参考,使小提琴

http://jsfiddle.net/TKwhY/

这对我来说是新的,但是您只能返回nodeType 3的元素来获取文本节点

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