Is there a difference between setting aria-hidden on an element in JavaScript using the ariaHidden
property instead of the aria-hidden
attribute?
Example:
myElement.ariaHidden = isOpen ? "false" : "true";
or...
myElement.setAttribute("aria-hidden", isOpen ? "false" : "true");
I haven't seen a lot of use of the former example, usually it's always the latter using the setAttribute()
method. Is it just syntactic preference, or is there a performance consideration?
.setAttribute()
on average is very slightly slower than directly setting it with ariaHidden=
. I will state, the difference is so minuscule and will likely never make an impact. I ran 10 million tests with the script I had attached, and the results were:
"Time per operation using ariaHidden property: 0.0003465200 ms"
"Time per operation using setAttribute: 0.0004629700 ms"
"Setting via setAttribute was 0.0001164500 ms slower per operation."
const element = document.getElementById('testElement');
const iterations = 10_000_000;
function testAriaHiddenProperty() {
let start = performance.now();
for (let i = 0; i < iterations; i++) {
element.ariaHidden = i % 2 === 0 ? false : true;
}
let end = performance.now();
return (end - start) / iterations;
}
function testSetAttribute() {
let start = performance.now();
for (let i = 0; i < iterations; i++) {
element.setAttribute('aria-hidden', i % 2 === 0 ? 'false' : 'true');
}
let end = performance.now();
return (end - start) / iterations;
}
const propertyTimePerOp = testAriaHiddenProperty();
const attributeTimePerOp = testSetAttribute();
console.log(`Time per operation using ariaHidden property: ${propertyTimePerOp.toFixed(10)} ms`);
console.log(`Time per operation using setAttribute: ${attributeTimePerOp.toFixed(10)} ms`);
const difference = attributeTimePerOp - propertyTimePerOp;
if (difference > 0) {
console.log(`Setting via setAttribute was ${difference.toFixed(10)} ms slower per operation.`);
} else if (difference < 0) {
console.log(`Setting via ariaHidden property was ${Math.abs(difference).toFixed(10)} ms slower per operation.`);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Performance Comparison</title>
</head>
<body>
<div id="testElement" style="width: 100px; height: 100px; background-color: lightblue;">Test Element</div>
</body>
</html>