Search code examples
javascriptpuppeteerplaywrighthtmlelements

How to remove a child from a puppeteer/playwright JSelement node and then fetch innerText


I'm able to fetch the cell using playwright/puppeteer. I want to capture the following two values separately - Date and the status.

I have the following code:

  let allCells = await allRows[0].$$('[role="cell"]');

  let ele = await allCells[0].$('.description');
  let status = await (await ele.getProperty("innerText")).jsonValue();
       // I can get the status as 'uploaded' just fine using this

  allCells[0].removeChild(ele);    // this throws an error

  let uploadDate = await (await allCells[0]("innerText")).jsonValue();      

The error it throws is : TypeError: allCells[0].removeChild is not a function

console.log( allCells[0] ) returns: JSHandle@….

Here is a relevant portion of the HTML:

<html>
<body>
  <div role="cell" class="cell-body">
     <!---->Jul 11, 2021
     <div class="description">
        uploaded
     </div>
  </div>
</body>
</html>

Solution

  • Unfortunately, you cannot call web API methods (.removeChild) on JS or element handles in puppeteer (Node.js) context.

    You can try to get all the data in the browser context with something like this (.childNodes[0] will give you just the first text node till the <div class="description"> element):

    import puppeteer from 'puppeteer';
    
    const browser = await puppeteer.launch();
    
    const html = `
      <html>
      <body>
        <div role="cell" class="cell-body">
           Jul 11, 2021
           <div class="description">
              uploaded
           </div>
        </div>
      </body>
      </html>`;
    
    try {
      const [page] = await browser.pages();
    
      await page.goto(`data:text/html,${html}`);
    
      const data = await page.evaluate(() => {
        const date = document.querySelector('div.cell-body').childNodes[0].textContent.trim();
        const description = document.querySelector('div.description').innerText;
        return [date, description];
      });
      console.log(data);
    } catch (err) { console.error(err); } finally { await browser.close(); }