Larry Lu Larry Lu - 9 months ago 40
Node.js Question

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.
I'm in A, too.

If I use
to select, I will also get
I'm in A and B
. But I just want to get
I'm in A
I'm in A, too
. How do I select the part I want.


Instead, of using .text, use .contents to get all of the nodes (including text nodes), then use each to loop through them and only get the text of the text nodes:

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

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

(Actual logged contents will likely have whitespace around them as that whitespace is in the text node, depending on the exact markup.)

Or if you prefer:

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

Which looks a lot tidier in ES2015+:

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