Reviewing a concatenated accessible name

In the example below, the <button> element's accessible name is concatenated into a text string from the accessible names of all of its descendant elements. The button below has an accessible name of:

Hello how are you doing today ?

Button example

<button>
  <svg aria-label="Hello"></svg>
  <span class="sr-only">how are you</span>
  <span role="img" aria-label="doing"></span>
  <span role="img" aria-labelledby="aaa"></span>
  <span role="img" title="?"></span>
</button>

<p id="aaa" style="display: none;">today</p>

Explanation

Line 1:

Buttons use “name from contents”, meaning their accessible name is built from the accessible text alternatives of descendant content. Different child elements can contribute text in different ways, and the final name is concatenated together.

The SVG provides an accessible name via aria-label="Hello"

<svg aria-label="Hello"></svg>

Line 2:

Even though visually hidden, the first <span> provides text: "how are you". Buttons build their accessible name from descendant content, so visually hidden text can still participate in the button’s name calculation. This works because the content is visually hidden only. It would not work if the element used display: none, visibility: hidden, or aria-hidden="true".

<span class="sr-only">how are you</span>

Line 3:

The second <span> has a role of img and therefore provides a name via aria-label: "doing"

<span role="img" aria-label="doing"></span>

Line 4:

The third <span> has a role of img and therefore provides a name via aria-labelledby: "today"

<span role="img" aria-labelledby="aaa"></span>
...
<p id="aaa" style="display: none;">today</p>

Notice that the referenced <p> uses display: none, yet “today” is still included. Hidden content is normally ignored, but aria-labelledby is the exception: it can pull text from elements that are hidden.

Line 5:

The fourth <span> has a role of img and therefore provides a fallback accessible name via the title: "?"

<span role="img" title="?"></span>

Why is there a space before the question mark?

Hello how are you doing today ?

The space is added by the browser when it builds the accessible name. Each <span role="img"> gets its text from an attribute (aria-labelledby and title), not from text content inside it. Chrome treats each of these as a separate piece and joins them with a space, so the title on the last span produces "today ?" rather than "today?".

Plain text is different. Inline text with no whitespace between elements runs together exactly as written.

Try it

Compare these two buttons in your browser's accessibility inspector. Both have no whitespace between their spans.

The browser decides how these pieces are joined, and browsers aren't perfectly consistent, so always check the computed name in each browser rather than assuming.