Oleksiy
Oleksiy

Reputation: 131

Puppeteer: How can I wait until a list is closed? How can I wait until an element is disappeared from the DOM?

Сase: There is a list in which you need to select an item, then it closes. When you click on another item the list does not have time to close. Finally there is one more click on another list element.

await page.waitForSelector('.list');
await page.click('.list');
await page.waitForSelector('.list-element');
await page.click('.list-element'); // click on the list element and list closes
await page.click('.another-element'); // click on the list

Upvotes: 13

Views: 9604

Answers (2)

Vishal Aggarwal
Vishal Aggarwal

Reputation: 4178

For waiting for an element to disappear from DOM, you need to start waiting first for the element to disappear before the action which makes it so:

   // Define the selector for the spinner (or element that needs to disappear)
const waitingSpinner = '.spinner-class';

await Promise.all([
  // Wait for the spinner to disappear (detached state means it's removed from the DOM)
  page.waitForSelector(waitingSpinner, { state: 'detached' }),

  // Perform the action that triggers the spinner's disappearance
  page.click('button#trigger-spinner')
]);

// Proceed with the next action once the spinner is confirmed to be gone

Upvotes: 4

javaLover
javaLover

Reputation: 39

Try this:

await page.waitForSelector('.list', {state: 'hidden'});

await page.waitForSelector('.list');
await page.click('.list');
await page.waitForSelector('.list-element');
await page.click('.list-element');
await page.waitForSelector('.list', {state: 'hidden'});
await page.click('.another-element');

This is the API Documentation: https://playwright.dev/docs/api/class-page#page-wait-for-selector

Upvotes: 0

Related Questions