JSFiddle - React, Tailwind, and code Playground

by davidpauljunior

HTML

<button data-test-aria>
Setting some aria with JS
</button>

JavaScript

function setAria(elem, attributes) {
	Object.entries(attributes).forEach(([key, value]) =>
		elem.setAttribute(`aria-${key}`, value)
	);
}

function toggleAria(elem, attributes) {
		attributes.forEach(attribute => {
			const attributeState = elem.getAttribute(`aria-${attribute}`) === "true";
      elem.setAttribute(`aria-${attribute}`, `${!attributeState}`);
    });
}

const testElem = document.querySelector('[data-test-aria]');

setAria(testElem, {
	expanded: "false",
	controls: "#a-thing"
});

testElem.addEventListener('click', () => 
	toggleAria(testElem, ["expanded"])
);