# @wdio/elements Element detection and locator generation for WebdriverIO — browser DOM querying, mobile page-source parsing, accessibility tree extraction, and AI-readable snapshots. ## Install ```bash npm install @wdio/elements ``` Peer dependency: `webdriverio` `^9.0.0 || ^10.0.0`. Optional peer: `@wdio/snapshot` `^10.2.0`, the snapshot renderer (see below). ## Usage ### Unified entry point (auto-detects browser vs mobile) ```ts import { getElements } from '@wdio/elements' const result = await getElements(browser, { limit: 50, inViewportOnly: true }) // { total, showing, hasMore, elements, tree? } ``` ### Accessibility snapshot (`getSnapshot`) Returns the accessibility tree as text: each actionable element gets an `eN` ref, and on the snapshot renderer its line ends in `→ `. The renderer follows the installed versions: - **Below 10.2** (9.x, 10.0, 10.1): the legacy renderer, which keeps this package's previous output. Do not install `@wdio/snapshot` on these versions: npm refuses it or nests a WebdriverIO 10 under your WebdriverIO 9. - **10.2 up to (not including) 11, prereleases included**, with `@wdio/snapshot` 10.x from 10.2 resolvable: `@wdio/snapshot`, the renderer behind `wdio session snapshot --selectors`. - **10.2 up to 11 without a resolvable `@wdio/snapshot` 10.x from 10.2**: the legacy renderer. It warns when an `@wdio/snapshot` outside 10.x from 10.2 is resolvable or resolution fails, and is silent only when `@wdio/snapshot` is not installed. With npm, `@wdio/cli` 10.2 already brings `@wdio/snapshot` (through `@wdio/session`), so a WebdriverIO 10.2 project that installed the CLI renders with `@wdio/snapshot` unless it removes it. Without the CLI, install it yourself (`npm i -D @wdio/snapshot`, a `^10.2.0` release). ```ts import { getSnapshot } from '@wdio/elements' const { format, text, elements, refs } = await getSnapshot(browser, { inViewportOnly: true }) // text: '- button "start" [ref=e1] → ~start' (one line per node) // elements: { e1: { selector, tagName, role, text } } // refs: SnapshotRef[], on format 'snapshot' only ``` The result fields: - `format`: `'snapshot'` or `'legacy'`, the renderer that produced the result. - `text`: the tree with `eN` refs. - `elements`: each ref's selector, role and name. On the snapshot path `tagName` is empty. - `refs`: the `SnapshotRef[]` behind the text, on the snapshot path only. On the snapshot path a ref can carry no selector: when the page yields no unique candidate selector for it, under any transport, it has no `elements` entry and its line in `text` has no `→` part (its candidates stay in `refs`). Options: `inViewportOnly`. The default is viewport-only on both renderers. Pass `{ inViewportOnly: false }` for the full page, which is much larger on long pages. `snapshotRenderer()` returns `'snapshot'` when the installed `webdriverio` and the resolved `@wdio/snapshot` are both 10.x from 10.2 (prereleases included, which semver's `^10.2.0` would reject), else `'legacy'`. WebdriverIO 11 stays on legacy until a release declares it. If `@wdio/snapshot` is installed but fails to load, `getSnapshot` falls back to legacy with a warning, `snapshotRenderer()` returns `'legacy'` from then on, and the result's `format` is the authoritative answer. Native sessions (`platformName` of Android, iOS, Mac or Windows with no `browserName`) parse the page source on the snapshot path. Only collection failures `@wdio/snapshot` raises are `SnapshotError`s; they and driver errors propagate, driver errors unchanged. Two exceptions: a failed page-source read logs a warning and returns `text: '[No elements found]'` with empty `elements` and `refs`; and if the driver cannot report the window size a native viewport snapshot reads, the whole tree is rendered, as on the legacy path. If nothing in the page source intersects the window, the whole tree is rendered too, as `wdio session snapshot` does; the legacy path instead collapses off-screen containers to placeholders. The DevTools **per-action trace capture** is a separate path with its own page scripts, so a locator in a trace can differ from the one `getSnapshot` renders. Differences from the CLI, whose session holds state this function does not have. The renderer and selector logic are shared: - The CLI session installs a page recorder that marks elements with JS click listeners as clickable. A plain `getSnapshot` has none, so a control with only a click listener gets no ref. - The CLI appends a `Requests failed:` note. - The CLI numbers refs across the actions of its session. Here they start at `e1` on every call. `@wdio/devtools-service`'s `browser.getSnapshot()` calls this function passing your options through, so it reads the visible viewport unless you pass `{ inViewportOnly: false }`. If the call fails it logs a warning and returns `{ format: 'legacy', text: '[Snapshot unavailable]', elements: {} }` instead of throwing, since nothing rendered; the `getSnapshot` exported here throws. ### Browser ```ts import { getInteractableBrowserElements } from '@wdio/elements' const elements = await getInteractableBrowserElements(browser, { includeBounds: true, inViewportOnly: true }) ``` ```ts import { getBrowserAccessibilityTree } from '@wdio/elements' const nodes = await getBrowserAccessibilityTree(browser, { inViewportOnly: true }) ``` ### Mobile ```ts import { getMobileVisibleElements } from '@wdio/elements' const elements = await getMobileVisibleElements(browser, 'ios', { includeBounds: true, includeContainers: false }) ``` ### AI-readable snapshots ```ts import { getBrowserAccessibilityTree, serializeWebSnapshot } from '@wdio/elements' const nodes = await getBrowserAccessibilityTree(browser, { inViewportOnly: true }) const text = serializeWebSnapshot( nodes, { url: await browser.getUrl(), title: await browser.getTitle() }, { inViewportOnly: true } ) ``` ```ts import { serializeMobileSnapshot } from '@wdio/elements' import { xmlToJSON } from '@wdio/elements/locators' const sourceXML = await browser.getPageSource() const root = xmlToJSON(sourceXML) const text = root && serializeMobileSnapshot( root, { platform: 'android', sourceXML }, { inViewportOnly: true } ) ``` ### Locator generation ```ts import { generateAllElementLocators, xmlToJSON } from '@wdio/elements/locators' const locators = generateAllElementLocators(pageSource, { platform: 'android', viewportSize: { width: 1080, height: 2340 } }) ``` ## API ### `getElements(browser, params)` Auto-detects platform and returns a unified result. | Param | Type | Default | Description | |---|---|---|---| | `inViewportOnly` | `boolean` | `true` | Skip off-screen elements | | `includeContainers` | `boolean` | `false` | Include layout containers (mobile only) | | `includeBounds` | `boolean` | `false` | Include element bounding boxes | | `limit` | `number` | `0` | Max elements (0 = no limit) | | `offset` | `number` | `0` | Pagination offset | ### `getSnapshot(browser, options)` Returns `GetSnapshotResult` — `{ format, text, elements, refs? }`; see [Accessibility snapshot](#accessibility-snapshot-getsnapshot) for the fields. | Param | Type | Default | Description | |---|---|---|---| | `inViewportOnly` | `boolean` | `true` | Only include what intersects the viewport | ### `snapshotRenderer()` Returns the `SnapshotFormat` (`'legacy' | 'snapshot'`) the next `getSnapshot` call will try; see [Accessibility snapshot](#accessibility-snapshot-getsnapshot) for how it is chosen. The result's `format` is authoritative. ### `SnapshotError` Thrown by `getSnapshot` on the snapshot path when `@wdio/snapshot` fails to collect. Carries `code` (string) and an optional `hint`; driver errors are not wrapped. ### `getInteractableBrowserElements(browser, options)` Single `querySelectorAll` walk — returns flat list of interactable elements. ### `getBrowserAccessibilityTree(browser, options)` Single DOM walk returning the accessibility tree as a flat `AccessibilityNode[]`. ### `getMobileVisibleElements(browser, platform, options)` Parses page source XML (2 HTTP calls total) and returns elements with generated locators. ### `@wdio/elements/locators` Re-exports the full locator generation pipeline from `@wdio/devtools-core`: - `xmlToJSON`, `xmlToDOM`, `evaluateXPath`, `checkXPathUniqueness` - `findDOMNodeByPath`, `parseAndroidBounds`, `parseIOSBounds` - `flattenElementTree`, `countAttributeOccurrences`, `isAttributeUnique` - `isInteractableElement`, `isLayoutContainer`, `hasMeaningfulContent` - `shouldIncludeElement`, `getDefaultFilters` - `getSuggestedLocators`, `getBestLocator`, `locatorsToObject` - `generateAllElementLocators` ## Types ```ts export type { BrowserElementInfo, GetBrowserElementsOptions, MobileElementInfo, GetMobileElementsOptions, AccessibilityNode, VisibleElementsResult, GetSnapshotOptions, GetSnapshotResult, SnapshotFormat, SnapshotResult, SnapshotElement, CandidateKind, SnapshotCandidate, SnapshotRef } from '@wdio/elements' // From @wdio/elements/locators: export type { ElementAttributes, JSONElement, Bounds, FilterOptions, UniquenessResult, LocatorStrategy, LocatorContext, ElementWithLocators, GenerateLocatorsOptions } from '@wdio/elements/locators' ```