Puppeteer - How to get innerText ignoring children

Viewed 379

I am looking to get the innerText of a h3 but I would like to ignore the nested span.

Example:

<h3>
    <span>NEW</span>
    Blog Article #69
</h3>

Here's my current code:

const title = await blogArticle.$eval(
    "h3",
    (el) => el.textContent
  );

It returns

NEWBlog Article #69

Also tried innerText with no success and I can't manage to delete the span from the DOM.

1 Answers

As long as the H3 does not contain any more tags this will work

'use strict';

const puppeteer = require('puppeteer');

const html = `
<html>
    <body>
    <h3>
    <span>NEW</span>
    Blog Article #69
    </h3>    
  </body>
</html>`;

(async () => {
  const browser = await puppeteer.launch({ headless : false});
  const page = await browser.newPage();
  await page.goto(`data:text/html,${html}`);
  const title = await page.$eval(
    "h3",
    (el) => el.innerHTML
  );

  const span = await page.$eval(
    "h3 span",
    (el) => el.innerText
  );

  var h3WithoutSpan = title.replace(`<span>${span}</span>`, "" ).trim();
  console.log("-->" + h3WithoutSpan);

  await browser.close();
})();

This returns -->Blog Article

This does the following

  1. Gets the inner HTML of H3
  2. Gets the text of the span (assume this can be other words than just NEW)
  3. Removes <span>NEW</span> and then any white space
Related