How to get element value in puppeteer

How to get element value in puppeteer or count element count using puppeteer. In this puppeteer tutorial, We will see an example on puppeteer to get a value from an element and find the count of elements.

Get Element value in puppeteer

page.$eval() function is used to get the value for an element in puppeteer. $eval will stage two-parameter as an argument first parameter will be the selector and the second parameter will be element= element.textContent.

Example:

const Message =  await page.$eval('H1', ele => ele.textContent);
console.log("Heading text: "+Message);

Get element count using puppeteer

Puppeteer does not have any pre-function to get count number of elements but its simple to get the count. We have a $$eval() function to get the count of an element with the same selector.

Let’s say we need to count <p> tag on a page.

const count =  await page.$$eval('p', ele => ele.length);
console.log("Count p tag in the page: "+count);

So here we are using eval function with $$ and in the above example eval function with $. Let understand the difference in eval function.

Difference between $eval() and $$eval()

$eval() function will use to perform any operation with a single element and $$eval() function is used to get the multiple-element from a web page.

$eval() will return a element and $$eval() will return the list of element.

Example to get Element and element Count using Puppeteer

In this puppeteer example, Test Scenario is:

Launch the browser and navigate to the URL.

Get the page heading text.

and count the number of the paragraph on the page.

close the browser.

const puppeteer = require('puppeteer')

describe("Home Page TestSuite",()=>{
     it("Handle Input and buuton in puppeteer",async()=>{
    const browser = await puppeteer.launch({
      headless:false,
      slowMo:100
    })
    const page = await browser.newPage()
    await page.goto("https://devexpress.github.io/testcafe/example/");
 
    // The text of H1 element..
    const Message =  await page.$eval('H1', ele => ele.textContent);
    console.log("Heading text: "+Message);

    const count =  await page.$$eval('p', ele => ele.length);
    console.log("Count p tag in the page: "+count);
    
    await page.waitFor(5000);
    await page.close();

  });

    });

Output: