I am trying to toggle an aria tag between true and false when a button is clicked. I've tried several implementations which seems to do absolutely nothing. Below is what I am currently using which successfully toggles the class. How can I extend this to toggle the aria-expanded value between true and false? Be easy on me, I am transitioning from jQuery to ES6.
const theTrigger = document.getElementById('mobile-form-control');
const theForm = document.querySelectorAll('.l-header__mobile-form');
theTrigger.onclick = function () {
for (const x of theForm) {
x.classList.toggle('show');
}
};
I am trying to toggle an aria tag between true and false when a button is clicked. I've tried several implementations which seems to do absolutely nothing. Below is what I am currently using which successfully toggles the class. How can I extend this to toggle the aria-expanded value between true and false? Be easy on me, I am transitioning from jQuery to ES6.
const theTrigger = document.getElementById('mobile-form-control');
const theForm = document.querySelectorAll('.l-header__mobile-form');
theTrigger.onclick = function () {
for (const x of theForm) {
x.classList.toggle('show');
}
};
Share
Improve this question
edited Nov 8, 2021 at 19:02
Robert E
asked Nov 8, 2021 at 18:39
Robert ERobert E
7404 gold badges17 silver badges29 bronze badges
3
- I pasted the wrong bit of code :/ I've updated my question. – Robert E Commented Nov 8, 2021 at 19:05
- ARIA attributes are no different than other HTML attributes and can be changed with setAttribute() as @connexo recommended. – slugolicious Commented Nov 9, 2021 at 0:27
- On StackOverflow, you are required to manage your questions' lifecycle. That means, that if you get answers, and they solve your problem, pick the answer that answers it best. If not, comment on the answers given and explain why these do not help you solve your problem. – connexo Commented Nov 9, 2021 at 21:22
3 Answers
Reset to default 11As of Firefox 119, you can use the ariaExpanded
API to toggle true
/false
on that attribute:
x.ariaExpanded = x.ariaExpanded !== 'true';
NOTE: ariaExpanded
returns a string, so you cannot use the logical NOT (!) operator by itself.
Assuming x
in your for-loop is the element you want to toggle the aria-expanded
attribute on:
theTrigger.onclick = function () {
for (const x of theForm) {
x.classList.toggle('show');
x.setAttribute(
'aria-expanded',
`${(x.getAttribute('aria-expanded') !== 'true').toString()}`
);
}
};
An inline attribute onclick js can be used when there are a few aria-expanded to set:
<details>
<summary
aria-expanded="false"
onclick="(() => { this.setAttribute('aria-expanded', this.getAttribute('aria-expanded') === 'true' ? 'false' : 'true'); })()"
>Click on summary</summary>
The content of the details…
</details>