Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessibility JS Function "Role" Attribute

I'm trying to write a JS function that would give empty heading elements (h1, and h2...)a “role” attribute value of “presentation”.

This is my first time working with accessibility in my projects and would love some help!

like image 876
JuniorDev Avatar asked Jul 11 '26 09:07

JuniorDev


1 Answers

If they're empty, do they need to be there at all? The most correct thing is just to remove them.

However, you can use document.querySelectorAll() to get all the headings, then look inside each one to see whether they are empty. If they are, you can set the role attribute. The following code is very quick and dirty, but will get you some of the way.

var headings = document.querySelectorAll("h1,h2,h3,h4,h5,h6");
// iterate through each heading
Array.prototype.forEach.call (headings, function (node) {
    // remove all white space
    var theTextContent = node.textContent.replace(/\s/g,'');
    // see if there's anything left in the string
    if (theTextContent.length < 1) {
        // node contains no visible text, mark it as presentation
        node.setAttribute("role", "presentation");
    }
} );

BUT this is a risky heuristic. Some headings might not contain text nodes, yet still appear as text on screen (e.g. they may have a background image in CSS representing a text in bitmap form). Instead of adding role="presentation" to these, you absolutely should add an aria-label with the correct heading text, otherwise you'll be violating at least two WCAG success criteria. ("Images of Text" and "Headings and Labels").

If you were using style attributes it might look something like this:

<h1 aria-label="welcome" style="background:url(welcome.png);"></h1>

like image 166
brennanyoung Avatar answered Jul 14 '26 02:07

brennanyoung