我如何 select 在 javascript 中使用 cheerio 的文本区域

How do I select the text area using cheerio in javascript

示例:

<div class="A">
    I'm in A.
    <h1 class="B">
           I'm in A and B.          
    </h1>
    I'm in A, too.
</div>

如果我用$('div.A').text()到select,我也会得到I'm in A and B。但我只想得到 I'm in AI'm in A, too。我如何select我想要的部分。

而不是使用 .text,使用 .contents 获取所有节点(包括文本节点),然后使用 each 循环遍历它们并只获取文本文本节点:

var text = [];
$("div.A").contents().each(function() {
    if (this.nodeType === 3) { // 3 = Text node
        text.push(this.nodeValue);
    }
});

console.log(text); // ["I'm in A.", "I'm in A, too."]

(实际记录的内容周围可能会有空格,因为该空格位于文本节点中,具体取决于确切的标记。)

或者如果您愿意:

var text = $("div.A")
    .contents()
    .filter(function() {
        return this.nodeType === 3; // 3 = Text node
    })
    .map(function() {
        return this.nodeValue;
    })
    .get();

在 ES2015+ 中看起来更整洁:

let text = $("div.A")
    .contents()
    .filter((i, e) => e.nodeType === 3)
    .map((i, e) => e.nodeValue)
    .get();

这个简单的技巧将有助于获得您想要的东西。

$('div.A')
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();

它基于克隆方法,您可以阅读更多相关信息from here

$('div.A').clone().children().remove().end().text() //single line representation