Difference between aria-label and aria-labelledby

Solution 1:

This site gives the reason for your answer:-

In theory, you should use aria-labelledby if the text is visually on-screen somewhere and this form is preferable. You should only use aria-label when it’s not possible to have the label visible on screen.

However, with current support, you should always use aria-labelledby, even if you need the label to be hidden. While at least JAWS 12 and VoiceOver both read the aria-label as expected, it turns out that VoiceOver doesn’t correctly read the hierarchy if aria-label is in use. For example:

<p id="group1">Outer group</p>
<p id="item1">First item</p>
<div role="group" aria-labelledby="group1">
<a href="javascript:" role="button" aria-labelledby="item1">Item Content</a>
</div>

everything here is using aria-labelledby and VoiceOver will read the button as “First item Outer group button”. In other words, the button label, the group label and then the type of object.

However, if you change any of the elements to use aria-label, for example:

<p id="item1">First item</p>
<div role="group" aria-label="Outer group">
<a href="javascript:" role="button" aria-labelledby="item1">Item Content</a>
</div>

VoiceOver will now read the button as simple “First item button”. It doesn’t seem to matter which item uses aria-label, if it’s anywhere in the hierarchy, only the label for the button itself will be read out.

From the MDN:-

The aria-labelledby attribute is used to indicate the IDs of the elements that are the labels for the object. It is used to establish a relationship between widgets or groups and their labels. Users of assistive technologies such as screen readers typically navigate a page by tabbing between areas of the screen. If a label is not associated with an input element, widget or group, it will not be read by a screen reader.

And this:-

The aria-label attribute is used to define a string that labels the current element. Use it in cases where a text label is not visible on the screen. (If there is visible text labeling the element, use aria-labelledby instead.)

Solution 2:

If you use aria-label, Screen reader speaks the value given for aria-label.

<p>accessibility</p>   <button aria-label="test">Click Me</button>

Screen Reader Output:

accessibility button test

If you have some text in webpage already there you can use aria-labelledby, you can simply give the id of that particular element to another element as value.

<p id="accessibilityLabel">accessibility</p>   <button aria-labelledby="accessibilityLabel">Click</button>

Screen Reader Output:

accessibility button accessibility