How to get all the applied styles of an element by just giving its id?
To get applied styles: use document.querySelector('#notion-app').getAttribute('style')
.
This will return as a string: "width: 1280px; max-width: 1280px; align-self: center; margin-top: 1px; margin-bottom: 1px;"
.
You can further break it into array by using .split(';')
.
To get computed styles (styles which get applied eventually):window.getComputedStyle(document.querySelector('#notion-app'))).cssText
Use the following method:
- Loop through the indexes of the
CSSStyleDeclaration
object (getComputedStyle) to get each known property name. UsegetPropertyValue
+ this name to get the value.
Code optimalization: Do not usegetComputedStyle
for each iteration, but store it in a variable outside the loop. - Use an ordinary
for ( name in object )
loop forcurrentStyle
. - Use the same looping method for inline styles
Code:
function getStyleById(id) {
return getAllStyles(document.getElementById(id));
}
function getAllStyles(elem) {
if (!elem) return []; // Element does not exist, empty list.
var win = document.defaultView || window, style, styleNode = [];
if (win.getComputedStyle) { /* Modern browsers */
style = win.getComputedStyle(elem, '');
for (var i=0; i<style.length; i++) {
styleNode.push( style[i] + ':' + style.getPropertyValue(style[i]) );
// ^name ^ ^ value ^
}
} else if (elem.currentStyle) { /* IE */
style = elem.currentStyle;
for (var name in style) {
styleNode.push( name + ':' + style[name] );
}
} else { /* Ancient browser..*/
style = elem.style;
for (var i=0; i<style.length; i++) {
styleNode.push( style[i] + ':' + style[style[i]] );
}
}
return styleNode;
}