Testing role="alert"
dynamically
Test versions: JAWS 2021, IE Edge, NVDA 2021.3.3, VoiceOver 12.4
1: Adding a new element with role="alert"
to the DOM dynamically: WORKS
Clicking the button below adds a new div with role="alert"
directly to the DOM. This is to check whether screen reader supports them being added dynamically, or if they have to be in the DOM already and have their contents changed later to be read out (like aria live regions do on some browsers).
el.insertAdjacentHTML('afterend', '<div role="alert">You need to fill in your username</div>');
Works in JAWS + IE, JAWS + Chrome, VO + Safari, VO + Firefox, NVDA + Firefox.
2: Adding role="alert"
to an existing element (which doesn't have that role) dynamically: does NOT work
errorMsg.setAttribute("role", "alert");
3: modifying the innerHTML of a role="alert"
element already in the DOM: WORKS
errorMsg.innerHTML = "You need to fill in your password.";
Works in JAWS + IE, JAWS + Chrome, VO + Safari, VO+ Firefox, NVDA + Firefox.
4: Making an invisible (display: none
) element already in the DOM visible: does NOT work
element.style.display
property is directly altered in JS
<div role="alert" style="display: none">Please enter your postcode</div>
...
errorMsg.style.display = "block";
(This also works if the div's style is initially set in a stylesheet rather than inline; what's important is that the modification needs to be done at the JS level)
<style id="myStyleElement"></style>
myStyleElement.innerHTML = "#errorMsg { display: block; }";
Notice the difference: we're modifying CSS only, but not via JS.
5: Making an invisible ([hidden]
attribute) element already in the DOM visible: does NOT work
errorMsg.removeAttribute("hidden");