---
title: Element Queries and Accessibility Identifiers | TestingBot
description: Every interaction in XCUITest starts with finding an element. This chapter
  shows how queries work, which ways of identifying an element survive app changes,…
source_url:
  html: https://testingbot.com/resources/courses/xcuitest/queries-and-accessibility-identifiers
  md: https://testingbot.com/resources/courses/xcuitest/queries-and-accessibility-identifiers.md
---

Course

[XCUITest Tutorial: iOS UI Testing in Swift](https://testingbot.com/resources/courses/xcuitest)

Chapter 3 of 11

1. [1 XCUITest Tutorial: iOS UI Test Automation in Swift](https://testingbot.com/resources/courses/xcuitest)
2. [2 Add a UI Test Target and Run Your First Test](https://testingbot.com/resources/courses/xcuitest/add-a-ui-test-target)
3. [3 Element Queries and Accessibility Identifiers](https://testingbot.com/resources/courses/xcuitest/queries-and-accessibility-identifiers)
4. [4 Interactions and Assertions](https://testingbot.com/resources/courses/xcuitest/interactions-and-assertions)
5. [5 Waiting Without sleep(): waitForExistence and Predicates](https://testingbot.com/resources/courses/xcuitest/waiting-without-sleep)
6. [6 Screen Objects in Swift](https://testingbot.com/resources/courses/xcuitest/screen-objects)
7. [7 Launch Arguments and Environment: Control App State](https://testingbot.com/resources/courses/xcuitest/launch-arguments-and-environment)
8. [8 Build for Testing: The App and the Test Runner](https://testingbot.com/resources/courses/xcuitest/build-for-testing)
9. [9 Run XCUITest on Real iPhones with TestingBot](https://testingbot.com/resources/courses/xcuitest/run-on-testingbot)
10. [10 XCUITest in CI with GitHub Actions](https://testingbot.com/resources/courses/xcuitest/ci-github-actions)
11. [11 XCUITest Knowledge Check](https://testingbot.com/resources/courses/xcuitest/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 3 of 11 Intermediate 7 min read 2 quick checks Updated Nov 2026 

# Element Queries and Accessibility Identifiers
On this page
1. [Queries are lazy descriptions](https://testingbot.com#queries-are-lazy-descriptions)
2. [Accessibility identifiers](https://testingbot.com#accessibility-identifiers)
3. [The query toolbox](https://testingbot.com#the-query-toolbox)
4. [See what XCUITest sees](https://testingbot.com#see-what-xcuitest-sees)

Every interaction in XCUITest starts with finding an element. This chapter shows how queries work, which ways of identifying an element survive app changes, and how to see the element tree XCUITest is working with.

## Queries are lazy descriptions[#](https://testingbot.com#queries-are-lazy-descriptions)

`app.buttons["login.submit"]` does not search the screen when you write it. It builds an `XCUIElement` that _describes_ how to find the element: "descendants of the app of type Button, matching login.submit". The search happens each time you use it: when you read `.exists`, call `.tap()` or read `.label`. That has two consequences:

- You can keep an element in a variable or property and reuse it across screens; it is re-resolved every time.
- If the description matches nothing at that moment, actions fail ("No matches found"), and if it matches more than one, actions fail too ("Multiple matching elements found"). A query that is ambiguous is a bug in the test, not bad luck.

The building blocks are element-type queries on `XCUIApplication` (or on any element):

| Query | SwiftUI / UIKit element |
| --- | --- |
| `app.buttons` | `Button`, `UIButton`, tappable list rows built from a `Button` |
| `app.staticTexts` | `Text`, `UILabel` |
| `app.textFields` | `TextField`, `UITextField` |
| `app.secureTextFields` | `SecureField`, secure `UITextField` |
| `app.navigationBars` | the navigation bar of a `NavigationStack` / `UINavigationController` |
| `app.cells`, `app.tables`, `app.collectionViews` | list and table content |
| `app.activityIndicators` | `ProgressView`, `UIActivityIndicatorView` |
| `app.otherElements` | containers and anything without a more specific type |
| `app.descendants(matching: .any)` | everything, regardless of type |

Picking the wrong type is the most common reason a query finds nothing. In the Tasks app the password field is a `SecureField`, so `app.textFields["login.password"]` never matches; it has to be `app.secureTextFields["login.password"]`.

## Accessibility identifiers[#](https://testingbot.com#accessibility-identifiers)

Subscripting a query with a string matches an element whose accessibility identifier or label equals that string. Labels are what users see and VoiceOver reads, so they change with copy edits and translations. **Accessibility identifiers** are strings meant for automation: users never see them and they do not change when the language does. Add them to every element a test touches.

In SwiftUI:

```swift
TextField("Email", text: $email)
    .textFieldStyle(.roundedBorder)
    .accessibilityIdentifier("login.email")
SecureField("Password", text: $password)
    .textFieldStyle(.roundedBorder)
    .accessibilityIdentifier("login.password")
Button("Sign in") { signIn() }
    .buttonStyle(.borderedProminent)
    .disabled(email.isEmpty || password.isEmpty || busy)
    .accessibilityIdentifier("login.submit")
```

In UIKit the property is the same name: `emailField.accessibilityIdentifier = "login.email"`.

A naming scheme such as `screen.element` keeps identifiers unique across the app and makes failure messages readable. Do not misuse `accessibilityLabel` for test hooks: VoiceOver users hear the label, so "login\_submit\_btn" there is an accessibility bug.

For repeated elements, give every row the _same_ identifier and tell them apart by label. The task rows in the Tasks app:

```swift
ForEach(store.tasks) { item in
    Button {
        store.toggle(item)
    } label: {
        HStack {
            Image(systemName: item.done ? "checkmark.circle.fill" : "circle")
            Text(item.title)
        }
    }
    .accessibilityIdentifier("task.row")
    .accessibilityLabel(item.title)
    .accessibilityValue(item.done ? "done" : "open")
}
```

The explicit label makes the row read as its title (instead of "circle, Buy milk"), and the value exposes its state to VoiceOver and to tests alike. Good accessibility and good testability are the same work here; the [Accessibility Testing course](https://testingbot.com/resources/courses/accessibility-testing) covers the user side.

Your tests use `app.buttons["Sign in"]`. They pass in English and fail when the suite runs with the German localisation. What is the fix?

 Give the button an accessibility identifier such as `login.submit` and query by that Set the button's `accessibilityLabel` to "Sign in" in every language Query `app.buttons.element(boundBy: 0)` instead

Identifiers are not localised and not shown to users, so they are stable across languages. Forcing an English label breaks VoiceOver for German users, and an index breaks as soon as another button appears before it.

## The query toolbox[#](https://testingbot.com#the-query-toolbox)

This test, from `QueryTests.swift`, uses every common way to narrow a query. The app is launched signed in with three tasks (chapter 6 shows how):

```swift
func testQueriesFindTheSeededTasks() throws {
    // By accessibility identifier: every row shares "task.row".
    let rows = app.buttons.matching(identifier: "task.row")
    XCTAssertEqual(rows.count, 3)

    // By label: the visible title.
    XCTAssertTrue(app.buttons["Call Anna"].exists)

    // By position: the first match of a query.
    XCTAssertEqual(rows.firstMatch.label, "Buy milk")
    XCTAssertEqual(rows.element(boundBy: 2).label, "Book flights")

    // By predicate: anything whose label starts with "Book".
    let book = app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Book"))
    XCTAssertEqual(book.count, 1)

    // Scoped: only text inside the navigation bar.
    let title = app.navigationBars.staticTexts["Tasks"]
    XCTAssertTrue(title.exists)
}
```

- **`matching(identifier:)`** returns a query (many elements); subscripting returns one element.
- **`count`** resolves the query and counts matches. Use it to assert list sizes.
- **`firstMatch`** stops at the first match instead of resolving the whole tree, which is faster on big screens. Use it when you know there is exactly one, or when "any of them" is fine.
- **`element(boundBy:)`** picks by index in tree order. Fine for "the third row of a list I just seeded"; fragile for anything whose order you do not control.
- **`NSPredicate`** matches on `identifier`, `label`, `value`, `placeholderValue`, `elementType`, `isEnabled`, `isSelected` and more, with `BEGINSWITH`, `CONTAINS`, `==` and regular expressions via `MATCHES`.
- **Chaining** (`app.navigationBars.staticTexts[...]`) scopes the search to descendants of the first match, which avoids picking up an identical text somewhere else on the screen.

## See what XCUITest sees[#](https://testingbot.com#see-what-xcuitest-sees)

When a query finds nothing, print the tree:

```swift
print(app.debugDescription)
```

An excerpt of the output for the task list with three seeded tasks (memory addresses and the plain `Other` wrappers SwiftUI adds are removed):

```
NavigationBar, {{0.0, 62.0}, {402.0, 54.0}}, identifier: 'Tasks'
  StaticText, {{178.3, 73.7}, {45.3, 20.7}}, label: 'Tasks'
  Button, {{295.0, 66.0}, {87.0, 36.0}}, identifier: 'tasks.signOut', label: 'Sign out'
TextField, {{16.0, 116.0}, {331.3, 34.0}}, identifier: 'tasks.newTitle', placeholderValue: 'New task'
Button, {{355.3, 122.7}, {30.7, 20.3}}, identifier: 'tasks.add', label: 'Add', Disabled
CollectionView, {{0.0, 160.7}, {402.0, 636.7}}, identifier: 'tasks.list'
  Cell, {{16.0, 195.7}, {370.0, 52.0}}
    Button, {{16.0, 195.7}, {370.0, 52.0}}, identifier: 'task.row', label: 'Buy milk', value: open
      Image, {{33.3, 213.3}, {17.0, 17.0}}, identifier: 'circle', label: 'circle'
      StaticText, {{59.7, 211.5}, {64.3, 20.3}}, label: 'Buy milk'
  ...
StaticText, {{174.5, 803.7}, {53.0, 20.3}}, identifier: 'tasks.count', label: '3 open'
```

Every line is type, frame, identifier, label, value and state. Notice that the row's title also exists as a `StaticText` inside the button: `app.staticTexts["Buy milk"]` and `app.buttons["Buy milk"]` are two different elements, and only the button carries the `open`/`done` value. It tells you at once whether the element exists under a different type, has no identifier, or is disabled. Two other tools show the same information interactively: Xcode's **Accessibility Inspector** (Xcode \> Open Developer Tool) and a breakpoint in a test followed by `po app.debugDescription` in the debugger console.

`app.buttons["task.row"].tap()` fails with "Multiple matching elements found". What should the test do instead?

 Add a `sleep(1)` before the tap Switch to `app.otherElements["task.row"]` Give each row a random identifier Pick the row it means, for example `app.buttons["Buy milk"]` or `app.buttons.matching(identifier: "task.row").element(boundBy: 0)`

The query is ambiguous because all rows share the identifier, which is by design. Waiting does not change the number of matches, a different element type finds nothing, and random identifiers cannot be queried at all.

Next: tapping, typing, swiping, and asserting on what changed.

[Previous · Chapter 2 Add a UI Test Target and Run Your First Test](https://testingbot.com/resources/courses/xcuitest/add-a-ui-test-target) [Next · Chapter 4 Interactions and Assertions](https://testingbot.com/resources/courses/xcuitest/interactions-and-assertions)

On this page

1. [Queries are lazy descriptions](https://testingbot.com#queries-are-lazy-descriptions)
2. [Accessibility identifiers](https://testingbot.com#accessibility-identifiers)
3. [The query toolbox](https://testingbot.com#the-query-toolbox)
4. [See what XCUITest sees](https://testingbot.com#see-what-xcuitest-sees)

Certification

Earn the free, resume-worthy TestingBot XCUITest Certification for this course.

[How it works](https://testingbot.com/resources/courses/xcuitest/certification)
