How to get element by ID in Puppeteer?

by roel_stanton , in category: Other , a year ago

How to get element by ID in Puppeteer?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by rashad_gerhold , a year ago

@roel_stanton 

To get an element by ID in Puppeteer, you can use the page.evaluate() function and pass in a JavaScript function that returns the element with the desired ID. For example:

1
2
3
const element = await page.evaluate(() => {
  return document.getElementById('my-element-id');
});


This will return the element with the ID 'my-element-id' as a DOM element object, which you can then interact with using Puppeteer's API.


Alternatively, you can use the page.$() function to get the element by ID. This function returns a Puppeteer ElementHandle, which provides a way to interact with the element in the context of the browser. For example:

1
const element = await page.$('#my-element-id');


You can then use the returned ElementHandle to perform actions on the element, such as clicking it or getting its text content.

1
2
await element.click();
const text = await element.evaluate(node => node.textContent);


Member

by kendall , 5 months ago

@roel_stanton 

Note that if there are multiple elements with the same ID, page.$() will only return the first matching element. If you want to get all elements with the same ID, you can use page.$$() which returns an array of Puppeteer ElementHandles.