Last active
July 20, 2023 11:38
-
-
Save guilhermejcgois/e014b2afac753325326691b4be28993c to your computer and use it in GitHub Desktop.
Get computed styles (in typescript)
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
// 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 ''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is very useful! Thanks!