Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

I have the following element:

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">

I want to use jquery (or just javascript would work) to alter the aria-expanded field to toggle it between true and false.

How would I go about this?

Thanks!

like image 564
Bren Avatar asked Jan 03 '15 06:01

Bren


People also ask

How to change aria-expanded value in jQuery?

But if you wish to do this using plain JS, you can use el. setAttribute("aria-expanded", true); where el is the element which can obtained using getElementById or querySelector or getElementsByClassName .

How do you make Aria-expanded false?

If specified when the menu is hidden, it should be set as aria-expanded="false" . When a child menu is not visible, its parent menuitem has aria-expanded . It should be set to true when the child menu is visible.

How do I expand my aria value?

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. From there you just get the value, and that should give you "false" (in this case).


2 Answers

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");
like image 68
gehleh Avatar answered Oct 19 '22 11:10

gehleh


Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

const button = document.querySelector('button');

button.addEventListener('click', () => {
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);
})
button[aria-expanded="true"] {
  color: red;
}
<button type="button" aria-expanded="false">Click me!</button>
like image 2
volt Avatar answered Oct 19 '22 10:10

volt