# Selectors and waiting

> Find elements with CSS, an id, a search or JavaScript, and wait for the page instead of sleeping.

The page: https://chromedp.dev/concepts/selectors/

An action such as `chromedp.Click` or `chromedp.Text` takes a selector. The
type of the selector says how chromedp finds the element.

## The selectors

| Selector | What it finds |
| --- | --- |
| `chromedp.CSS("form input")` | the first element that matches a CSS selector |
| `chromedp.CSSAll("li")` | every element that matches a CSS selector |
| `chromedp.ID("name")` | the element with the id. The `#` is optional |
| `chromedp.Search("//button")` | the elements that a search finds: plain text, a CSS selector or an XPath query |
| `chromedp.JSPath("document.forms[0]")` | the elements that a JavaScript expression returns |

A plain string, such as `chromedp.Click("#greet")`, is a `chromedp.Search`.
Use `chromedp.CSS` when you mean CSS: it is faster and it finds what you
expect. Use `chromedp.JSPath` only with your own expressions, because chromedp
sends the expression to the page as it is.

## A query waits

An action with a selector waits until the page has the element. It waits
until the context ends, so set a [timeout](/concepts/contexts/#timeouts) on
the context. Query options change what the action waits for:

| Option | What the action waits for |
| --- | --- |
| none | the element exists in the page |
| `chromedp.NodeVisible` | the element is visible |
| `chromedp.AtLeast(3)` | at least three elements match. `AtLeast(0)` returns at once |
| `chromedp.FromNode(node)` | the element is inside `node`, such as an iframe |

```go
text, err := chromedp.Run(ctx, chromedp.Text(chromedp.CSS("#result"), chromedp.NodeVisible))
```

The actions `chromedp.WaitVisible`, `chromedp.WaitReady` and
`chromedp.WaitNotPresent` wait and do nothing else.

## Wait for a condition

`chromedp.Poll` runs a JavaScript expression in the page until it returns a
true value, and returns that value:

```go
// Wait until the page has loaded its data.
ok, err := chromedp.Run(ctx, chromedp.Poll[bool](`document.title === "done"`))
```

It times out after 30 seconds. The option `chromedp.WithPollingTimeout`
changes the time. The tutorial [Intercept requests](/tutorials/intercept/)
uses `Poll`.

## Do not sleep

`chromedp.Sleep` waits for a fixed time, so it is too short on a slow day and
too long on a fast one. Wait for what the page shows instead: an element, a
text, or a condition of `Poll`.
