Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active April 1, 2024 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmorr/9283ac1a31f70fc45caf341da0bad2ae to your computer and use it in GitHub Desktop.
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
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