Larry Lu Larry Lu - 2 months ago 10
Node.js Question

How do I select the text area using cheerio in javascript

Example:

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


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

Answer

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
        text.push(this.nodeValue);
    }
});

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")
    .contents()
    .filter(function() {
        return this.nodeType === 3; // 3 = Text node
    })
    .map(function() {
        return this.nodeValue;
    })
    .get();

Which looks a lot tidier in ES2015+:

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