How To Get Only Text Node From Parent Using Node.js and Cheerio

Published on 8 Aug, 2021

Here is our HTML. The parent element has a child element(s) and immediate text nodes.

<div>
  <span>$</span>
  999
</div>

Inside div, we have an inner element(span) and also a text node(999). We need to extract only the text 999.

Using cheerio, we can do it like this:

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