Search code examples
javascriptjquerytoggleclass

Toggle Class Using Aria-Expanded


I have the following to toggle a span element's class based on the parent's aria-expanded attr value:

$(function () {
    if ($('.is-accordion-submenu-parent').attr('aria-expanded') === "true") {
        $(this).find(".typcn-arrow-sorted-down").toggleClass("typcn-arrow-sorted-up");
    }
})

Here's the structure:

<li class="is-accordion-submenu-parent" aria-expanded="false">
  <a>Label</a>
  <span class="typcn typcn-arrow-sorted-down"></span>
</li>

EDIT

  <li class="is-accordion-submenu-parent" aria-expanded="false">
    <a>Label<span class="typcn typcn-arrow-sorted-down"></span></a>
    <ul class=“nested”>
      <li class=“menu item”>…</li>
      …etc…
    </ul>
  </li>

A click on the a tag toggles the state, but this code doesn't work as expected. Any ideas?


Solution

  • Solved this by targeting the *-expanded attribute and after pseudo element with CSS.