How can I check that an element is visible with Puppeteer and pure JavaScript? How can I check that an element is visible with Puppeteer and pure JavaScript? javascript javascript

How can I check that an element is visible with Puppeteer and pure JavaScript?


I found that Puppeteer has an API method for this purpose: Page.waitForSelector, via its visible option. I wasn't aware of the latter option, but it lets you wait until an element is visible.

await page.waitForSelector('#element', {  visible: true,})

Conversely you can wait for an element to be hidden, via the hidden option.

I think this is the idiomatic answer, with regards to the Puppeteer API. Thanks to Colin Cline though as I think his answer is probably useful as a general JavaScript solution.


One is by checking its display style value.Second is by checking its height, for exp if the element is a child of an element which is display: none, the offsetHeight will be 0 and thus you know the element is not visible despite its display value. opacity: 0 is not considered as hidden element so we will not checking it.

const isNotHidden = await page.$eval('#menu', (elem) => {    return window.getComputedStyle(elem).getPropertyValue('display') !== 'none' && elem.offsetHeight});

You can check elem.offsetWidth as well and is not bad before any calculation, check if element exist or not.


Use boundingBox()

This method returns the bounding box of the element (relative to the main frame), or null if the element is not visible.

API: https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#elementhandleboundingbox