javascriptcsscss-selectorswai-aria

CSS selector computed aria name


Is it possible to select via a CSS selector (or xpath) an element based on its computed aria name (=accessible name)? For instance for buttons it is computed like

The button has an accessible label. By default, the accessible name is computed from any text content inside the button element. However, it can also be provided with aria-labelledby or aria-label.

I tried to use [aria-label=Foo] that is supposed to be global (edit: hence automatically defined for button based on their content), but it fails…

Motivation: robotframework-browser only allows text, css or xpath selectors in locators (and get by role is quite impractical to use as it involves an extra variable), and chrome recorder extension gives me aria-based selectors.

MWE: you can run it in here:

<script>
    let clickme = () => {
        console.log('foo', document.querySelectorAll('[aria-label=Hello]').length)
    };
</script>

<div class="preference">
  <label for="cheese">Do you like cheese?</label>
  <input name="cheese" id="cheese" />
</div>

<button>Hello</button>

<button onclick={clickme}>Click</button>

Solution

  • No, you can’t select elements by their computed accessible (ARIA) name using CSS or XPath.

    Summary:
    You can’t do it with pure CSS/XPath; use tool-specific queries or JS if you need this.