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

I wish to check that a DOM element is visible with Puppeteer and pure JavaScript (not jQuery), how can I do this? By visible I mean that the element is displayed through CSS, and not hidden (f.ex. by display: none).

For example, I can determine whether my element #menu is not hidden via CSS rule display: none, in the following way:

const isNotHidden = await page.$eval('#menu', (elem) => {
  return elem.style.display !== 'none'
})

How can I determine in general though if the element is hidden or not, and not just through display: none?

Answers


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.


I would use @aknuds1 's approach, but you can also do the following.

expect((await page.$('#element')) !== null).toEqual(true)

If you are fetching a resource asynchronously, be aware that the above expectation may not pass, since it won't wait for the changes to reflect on the UI. That's why this approach may not be preferred in this scenario.


Need Your Help

WPF - How do I get an object that is bound to a ListBoxItem back

c# wpf data-binding listbox listboxitem

here is what I would like to do. I get a List of objects from a database and bind this list to a ListBox Control. The ListBoxItems consist of a textbox and a button. Here is what I came up with. Up...