I am trying to dynamically change the value of a custom CSS variable using JavaScript. I initially attempted to use
element.style.["--my-custom-var"] = value
, but realized that it did not work for custom variables. After some research, I discovered that I can add custom CSS properties to an element using both element.setAttribute
and element.style.setProperty
. My question is: what is the difference between these two approaches? Specifically, which method offers better performance and which one is considered best practice when adding custom properties via JavaScript.
Example:
// Both of these code snippets are capable of adding a custom css rule to the inline style of an element
element.setAttribute('style','--my-custom-var: 10px;');
element.style.setProperty('--my-custom-var', '10px');