Skip to main content

$

Overview

Use the $ command instead of findElement as a shorter command to get a single element on the page.

The $ command returns an object describing the element, on which you can call action commands without passing the selector. However, if you pass a selector, it will first find the corresponding element and then call the action for that element. You can also pass an object as the selector, where the object contains the property element-6066-11e4-a52e-4f735466cecf with the value of the element reference. The command will then convert the reference into an extended WebdriverIO element.

You can chain $ or $$ together to traverse down the DOM tree.

info

Read more about how to select specific elements in the recipe "How to use selectors".

Usage

await browser.$(selector);

Command Parameters

NameTypeDescription
selectorString or Function or MatcherSelector or JS function to get a specific element.

Examples

index.html

<ul id="menu">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/">Developer Guide</a>
</li>
<li>
<a href="/">API</a>
</li>
<li>
<a href="/">Contribute</a>
</li>
</ul>

$.js

it("should get text of a menu link", async ({ browser }) => {
const text = await browser.$("#menu");

console.log(await text.$$("li")[2].$("a").getText()); // outputs: "API"
});

it("should get text of a menu link - JS Function", async ({ browser }) => {
const text = await browser.$(function () {
// Arrow function cannot be used here.
// This is Window – https://developer.mozilla.org/en-US/docs/Web/API/Window
//
// TypeScript users can do something like:
// return (this as Window).document.querySelector('#menu')
return this.document.querySelector("#menu"); // Element
});

console.log(await text.$$("li")[2].$("a").getText()); // outputs: "API"
});

it("should allow converting the protocol result of an element into a WebdriverIO element", async ({
browser,
}) => {
const activeElement = await browser.getActiveElement();

console.log(await browser.$(activeElement).getTagName()); // outputs the active element
});

it("should use Androids DataMatcher or ViewMatcher selector", async ({ browser }) => {
const menuItem = await browser.$({
name: "hasEntry",
args: ["title", "ViewTitle"],
class: "androidx.test.espresso.matcher.ViewMatchers",
});
await menuItem.click();

const menuItem = await browser.$({
name: "hasEntry",
args: ["title", "ViewTitle"],
});
await menuItem.click();
});

References

We'd like to give credit to the original WebdriverIO docs article, from which we drew some information while writing our version.