<span id="testElement">Test text</span>
var a = document.getElementById("testElement");
a.setAttribute("style","color:red");
a.style.color = 'red';
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
setAttribute | |
CSS properties |
Test name | Executions per second |
---|---|
setAttribute | 6621586.0 Ops/sec |
CSS properties | 4452169.0 Ops/sec |
This benchmark tests the performance of two methods for setting the text color of an HTML element:
setAttribute("style", "color:red")
: This method uses the setAttribute()
function to set the "style" attribute of the element with the value "color:red".
a.style.color = 'red'
: This method directly accesses the style
object of the element and sets the color
property to 'red'.
Pros and Cons:
setAttribute("style", ...)
:
a.style.color = 'red'
:
Other Considerations:
a.style.color = 'red'
approach is generally considered more readable and maintainable for simple style changes.Alternatives:
className
property. This provides better organization and reusability of styles.style
attribute. However, this can lead to code bloat and decreased maintainability.This benchmark helps you understand which method performs better in your specific browser environment for setting a simple text color.