How can I use Playwright to check if an element is hidden or not in the viewport?


Checking Element Visibility with Playwright

Playwright provides handy methods to check if an element is visible or not.

Using toBeHidden()

The toBeHidden() assertion from the LocatorAssertions class checks if a locator doesn't resolve to any DOM node or resolves to a non-visible one. Here's how you can use it:

const locator = page.locator('button');
await expect(locator).toBeHidden();

This code checks if a button on your page is hidden. If the button isn't visible, the assertion passes. If it's visible, the assertion fails.

Using toBeInViewport()

Playwright also offers the toBeInViewport() assertion. This checks if an element intersects with the viewport according to the intersection observer API. Here's how to use it:

const locator = page.locator('button');
await expect(locator).not.toBeInViewport(); // Asserts that at least some part of element is outside of viewport
await expect(locator).toBeInViewport({ ratio: 0.5 }); // Asserts that at least half of the element intersects with viewport

These assertions consider factors like bounding box, computed styles, and animation frames to accurately determine element visibility.

So, with Playwright, you can easily assert whether an element is visible or not from a user's perspective. This is useful for checking if an element is out of the viewport or covered by another element during automated testing.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.