Skip to content

Instantly share code, notes, and snippets.

@guilhermejcgois
Last active July 20, 2023 11:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save guilhermejcgois/e014b2afac753325326691b4be28993c to your computer and use it in GitHub Desktop.
Save guilhermejcgois/e014b2afac753325326691b4be28993c to your computer and use it in GitHub Desktop.
Get computed styles (in typescript)
// Gist adapted from: https://gist.github.com/cms/369133
export getStyle(el: Element, styleProp: string): string {
let value;
const defaultView = el.ownerDocument.defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, '-$1').toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el['currentStyle']) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el['currentStyle'][styleProp];
return value;
}
return '';
}
@lut2410
Copy link

lut2410 commented Aug 10, 2018

This code is very useful! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment