This example shows how ariaControlsElements
can be used to get the controlled elements that were set using aria-controls
.
The HTML defines first defines a <button>
element and two <div>
elements, panel1
and panel2
, that it controls. The references to the controlled panels are listed in the button's aria-controls
attribute.
<button id="toggleButton" aria-controls="panel1 panel2" aria-expanded="false">
Show Details
</button>
<div class="panel" id="panel1" aria-hidden="true">
<p>Panel1 opened/closed by button.</p>
</div>
<div class="panel" id="panel2" aria-hidden="true">
<p>Panel2 opened/closed by button.</p>
</div>
.panel {
display: none; /* Initially hidden */
border: 1px solid #ccc;
padding: 5px;
margin-top: 5px;
}
#log {
height: 70px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
JavaScript
The code first sets up the panels to be toggled open or hidden based on the aria-expanded
attribute of the button.
const logElement = document.querySelector("#log");
function log(text) {
logElement.innerText = `${logElement.innerText}${text}\n`;
logElement.scrollTop = logElement.scrollHeight;
}
const toggleButton = document.querySelector("#toggleButton");
const panel1 = document.querySelector("#panel1");
const panel2 = document.querySelector("#panel2");
toggleButton.addEventListener("click", () => {
const isExpanded = toggleButton.getAttribute("aria-expanded") === "true";
toggleButton.setAttribute("aria-expanded", !isExpanded);
panel1.style.display = isExpanded ? "none" : "block";
panel1.setAttribute("aria-hidden", isExpanded); //true when hidden, false when shown.
panel2.style.display = isExpanded ? "none" : "block";
panel2.setAttribute("aria-hidden", isExpanded); //true when hidden, false when shown.
});
Next the example gets the value of the aria-controls
attribute with Element.getAttribute()
(a string listing the id
values of the referenced elements). It then checks whether the ariaControlsElements
property is supported, and if so, logs its value. Finally it returns and logs the inner text for each of the controlled elements.
log(`aria-controls: ${toggleButton.getAttribute("aria-controls")}`);
// Feature test for ariaControlsElements
if ("ariaControlsElements" in Element.prototype) {
// Get ariaControlsElements
const controlledElements = toggleButton.ariaControlsElements;
log(`ariaControlsElements: ${controlledElements}`);
// List innerText for each of the ariaControlsElements
controlledElements.forEach((controlled) => {
log(` Controlled element text: ${controlled.textContent.trim()}`);
});
} else {
log("element.ariaControlsElements: not supported by browser");
}
Result
Click the button below to show and hide the panels. The log shows the original element references, the associated/returned elements, and the inner text of each element.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3