Skip to content

Instantly share code, notes, and snippets.

@twilight-sparkle-irl
Last active June 26, 2019 20:16
Show Gist options
  • Save twilight-sparkle-irl/e923d96ccb108799e0341e4209c3f99e to your computer and use it in GitHub Desktop.
Save twilight-sparkle-irl/e923d96ccb108799e0341e4209c3f99e to your computer and use it in GitHub Desktop.
an exercise in pain and suffering -- getting the set styles as an object from [element].style
// redundant_styles gets all the set styles, including ones that just set children value (text-decoration -> text-decoration-line, for example)
// implied_styles gets all the styles that are set and do not only affect the style by setting other properties
// all_styles gets all styles, unset or not. it's prety useless i just added it because it was possible
// getting the styles without the implied ones is not something i had time to do, it seems that i'd have to do text parsing to achieve that
style_to_obj = {}
if ('CSS2Properties'in window) { // firefox .style
style_to_obj['redundant_styles'] = (x=>Object.fromEntries(Object.keys((x.__proto__)).filter(_=>!_.match(/[A-Z]/g)).map(_=>[_,x.__lookupGetter__(_).bind(x)()]).filter(_=>_[1]!=='')))
style_to_obj['implied_styles'] = (x=>Object.fromEntries([...x].map(_=>[_,x[_]])))
style_to_obj['all_styles'] = (x=>Object.fromEntries(Object.keys((x.__proto__)).filter(_=>!_.match(/[A-Z]/g)).map(_=>[_,x.__lookupGetter__(_).bind(x)()]).filter(_=>_[1]!=='')))
} else { // chrome .style
style_to_obj['redundant_styles'] = (x=>(x=Object.entries(x),[...x.filter(_=>(_[1]!=="" && isNaN(_[0])))]).map(_=>[_[0].replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`),_[1]]).reduce((o,{0:k,1:v})=>Object.assign(o,{[k]:v}),{}))
style_to_obj['implied_styles'] = (x=>(x=Object.entries(x),[...x].map(_=>[_[0].replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`),_[1]]).filter(_=>([...x].filter($=>!isNaN($[0]))).map(_=>_[1]).includes(_[0])).reduce((o,{0:k,1:v})=>Object.assign(o,{[k]:v}),{})))
style_to_obj['all_styles'] = (x=>(x=Object.entries(x),[...x.filter(_=>(isNaN(_[0])))].map(_=>[_[0].replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`),_[1]])).reduce((o,{0:k,1:v})=>Object.assign(o,{[k]:v}),{}))
}
@twilight-sparkle-irl
Copy link
Author

twilight-sparkle-irl commented Jun 26, 2019

if you dare leave a comment telling me there's a bug i will destroy you.
please don't use this in production environments or for anything but messing around. i beg of you

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