Get aria-expanded value

In 2020, I could do:

document.querySelector('[aria-expanded]')?.getAttribute('aria-expanded')

to grab the first value and maybe something like:

Array.from(document.querySelectorAll('[aria-expanded]'))?
  .map(el => el.getAttribute('aria-expanded'))

to make an array of all aria-expanded values.


aria-expanded is an attribute on the element, not a class, so the selector is incorrect. Secondly, you should use the attr() function to get the value of that attribute. val() is intended to retrieve the value attribute from form related elements, such as input and textarea. Try this:

console.log($(this).find('a[aria-expanded]').attr('aria-expanded'));

You can use JavaScript to achieve this:

document.getElementsByTagName('a')[0].attributes[4].value

Step by step explanation:

  1. Get the wanted element, by using some selector - here I use the

    document.getElementsByTagName('a')[0]
    

but you can use any other selector you like.

  1. Access the attributes array of the element and find the position of the wanted attribute - in this case that will be 4, because aria-expanded is the 5th attribute of the tag.
  2. From there you just get the value, and that should give you "false" (in this case).

The only problem with this method is that it's a bit hard-coded, so if you add some more attributes to the tag, the position in the attributes array for the aria-expanded attribute might change.

UPDATE

Instead of using the index for accessing the Aria Expanded property, you can use the name:

document.getElementsByTagName('a')[0].attributes['aria-expanded'].value

This way you will always get the value for the Area Expanded property, regardless of it's position in the HTML tag.


I wanted to add in a second pure javascript way to get the aria-expanded attribute

document.getElementById('test').getAttribute('aria-expanded')

The above will get the element by id after that you can get any attribute by name.