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!
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 .
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.
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).
You can use .attr() as a part of however you plan to toggle it:
$("button").attr("aria-expanded","true");
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With