2

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');
  }
};

Robert E
  • 700
  • 3
  • 16
  • 29
  • I pasted the wrong bit of code :/ I've updated my question. – Robert E Nov 08 '21 at 19:05
  • ARIA attributes are no different than other HTML attributes and can be changed with setAttribute() as @connexo recommended. – slugolicious Nov 09 '21 at 00: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 Nov 09 '21 at 21:22

2 Answers2

4

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' 
        ? 'false' 
        : 'true'
    );
  }
};
connexo
  • 53,704
  • 14
  • 91
  • 128
4

It would be much easier with a simple toggle:

    x.ariaExpanded = !x.ariaExpanded;

But weirdly, Firefox doesn't support direct boolean access to the DOM property! https://developer.mozilla.org/en-US/docs/Web/API/Element/ariaExpanded#browser_compatibility

So I ended up with something like this:

    x.setAttribute(
      'aria-expanded', 
      `${!(x.getAttribute('aria-expanded') === 'true')}`
    );
Yann Dìnendal
  • 1,422
  • 2
  • 17
  • 27