When we are applying a lot of style changes using JavaScript to a single element, phpied & Writing Efficient JavaScript (slide 87) suggests:
instead of applying styles one by one using style.stylename, apply everything in one go using cssText or changing classname as it'll reduce reflows/repaints
Which is better when there's only a single style change?
document.getElementById('myid').style.cssText += ";color:#999;";
OR
document.getElementById('myid').style.color = "#999";
jsperf.com/csstext-vs-styles-single shows that when there's only a single style change, using individual style name is faster than cssText.
Are there any other factors also to be considered?
The cssText property of the CSSStyleDeclaration interface returns or sets the text of the element's inline style declaration only. To be able to set a stylesheet rule dynamically, see Using dynamic styling information. Not to be confused with stylesheet style-rule CSSRule.
To change the styles of all elements with a specific class: Use the querySelectorAll() method to get a collection of the elements with the specific class. Use the forEach() method to iterate over the collection. On each iteration, use the style object to change the element's styles.
I should use the individual stylename in your case, because you are going to change only one style. :)
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