Is there an equivalent to the "alt" attribute for div elements?

Kode_12 picture Kode_12 · Jul 14, 2016 · Viewed 36.7k times · Source

Screenreaders will read whatever string is set to the "alt" attribute. The use of this attribute is specifically for image tags.

If I have a div like so:

<div id=myCoolDiv tabindex="0"> 2 <div>

Is there a way to have a screen reader pickup an attribute to read a string the same way an alt tag is used?

So for the div listed below, the screen reader will say ie: "shopping cart items 2"?

I tried using aria-label but the screenreader won't pick it up:

<div id=myCoolDiv tabindex="0" aria-label="shopping cart items"> 2 <div>

Answer

Radek Pech picture Radek Pech · Jul 18, 2016

There are two ways (which can be combined) to have screen reader to read alternative text:

  1. Anything with ARIA role img can (MUST) have alt attribute. See WAI-ARIA img role.

    <div role="img" alt="heart">
    ♥︎
    </div>
    

However this should be used only in case the element really represent an image (e.g. the heart unicode character).

  1. If an element contain actual text, that just need different reading, you should set ARIA role to text and add aria-label with whatever you want to be read by the screen reader. See WAI-ARIA text role.

    <div role="text" aria-label="Rating: 60%">
    Rating: ★★★☆☆︎
    </div>
    

Do not mismatch it with aria-labeledby which should contain ID of an related element.

  1. You can combine the previous two cases into one using two ARIA roles and adding both alt and aria-label:

    <div role="img text" alt="heart" aria-label="heart">
    ♥︎
    </div>
    

When more ARIA roles are defined, browser should use the first one that is supported and process the element with that role.


One last important thing is that you must set page type to HTML5 (which support ARIA by design).

<!DOCTYPE html>

Using HTML4 or XHTML requires special DTD to enable ARIA support.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+ARIA 1.0//EN"
   "http://www.w3.org/WAI/ARIA/schemata/xhtml-aria-1.dtd">