Last active
April 1, 2024 20:14
-
-
Save ryanmorr/9283ac1a31f70fc45caf341da0bad2ae to your computer and use it in GitHub Desktop.
Get and set CSS styles, supporting camel-case, kebab-case, and custom properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getStyle(el, prop) { | |
const style = getComputedStyle(el); | |
return prop.includes('-') ? style.getPropertyValue(prop) : style[prop]; | |
} | |
function setStyle(el, prop, value) { | |
if (prop.includes('-')) { | |
el.style.setProperty(prop, value); | |
} else { | |
el.style[prop] = value; | |
} | |
} | |
// Usage: | |
getStyle(element, 'borderWidth'); | |
getStyle(element, 'border-width'); | |
getStyle(element, '--custom-prop'); | |
setStyle(element, 'backgroundColor', 'red'); | |
setStyle(element, 'background-color', 'red'); | |
setStyle(element, '--custom-prop', 'foo'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment