puppeteer/docs/api/puppeteer.elementhandle.waitforselector.md

98 lines
1.7 KiB
Markdown
Raw Normal View History

2022-07-05 13:41:43 +00:00
---
sidebar_label: ElementHandle.waitForSelector
---
# ElementHandle.waitForSelector() method
Wait for an element matching the given selector to appear in the current element.
2022-07-05 13:41:43 +00:00
Unlike [Frame.waitForSelector()](./puppeteer.frame.waitforselector.md), this method does not work across navigations or if the element is detached from DOM.
2022-07-05 13:41:43 +00:00
#### Signature:
2022-07-05 13:41:43 +00:00
```typescript
class ElementHandle {
waitForSelector<Selector extends string>(
2022-07-05 13:41:43 +00:00
selector: Selector,
options?: WaitForSelectorOptions
): Promise<ElementHandle<NodeFor<Selector>> | null>;
2022-07-05 13:41:43 +00:00
}
```
## Parameters
<table><thead><tr><th>
2022-07-05 13:41:43 +00:00
Parameter
</th><th>
Type
</th><th>
Description
</th></tr></thead>
<tbody><tr><td>
selector
</td><td>
Selector
</td><td>
The selector to query and wait for.
</td></tr>
<tr><td>
options
</td><td>
[WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md)
</td><td>
_(Optional)_ Options for customizing waiting behavior.
</td></tr>
</tbody></table>
2022-07-05 13:41:43 +00:00
**Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt; \| null&gt;
2022-07-05 13:41:43 +00:00
An element matching the given selector.
2022-07-05 13:41:43 +00:00
## Exceptions
2022-07-05 13:41:43 +00:00
Throws if an element matching the given selector doesn't appear.
2022-07-05 13:41:43 +00:00
## Example
2022-07-05 13:41:43 +00:00
```ts
import puppeteer from 'puppeteer';
2022-07-05 13:41:43 +00:00
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
let currentURL;
page
.mainFrame()
.waitForSelector('img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of [
'https://example.com',
'https://google.com',
'https://bbc.com',
]) {
await page.goto(currentURL);
}
await browser.close();
})();
```