Rayrun

How do I use Playwright to wait for an element to be removed from the DOM?

Answer

Waiting for an Element to Disappear in Playwright

In Playwright, you can use the waitForSelector method to wait until an element is no longer present in the DOM. This method takes a selector and a state option. Set the state option to "detached" to wait for the element to disappear.

If the selector already satisfies the "detached" state, the method returns immediately. If not, it waits for a specified timeout (in milliseconds). If the condition is not satisfied after the timeout, an exception is thrown.

Playwright automatically waits for elements to be ready before performing actions. But, using waitForSelector with "detached" lets you wait until an element is gone before performing further actions.

Here's an example in TypeScript:

import { chromium } from '@playwright/test';

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();

  // Navigate to ray.run
  await page.goto('https://ray.run');

  // Wait for an element with ID 'my-element' to disappear
  await page.waitForSelector('#my-element', { state: 'detached' });

  // Perform further actions once #my-element has disappeared

  await browser.close();
})();

In this example, we navigate to ray.run and wait for #my-element to disappear before performing further actions. This is a handy way to wait for an element to disappear in Playwright.

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 Questions

TwitterGitHubLinkedIn
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.