Reputation: 709
I was trying to write a function which takes the Id of an element and gives the list of all the style attributes(with their values) applied on that element. It should consider the inline style as well as the style defined in css file.
I could get the function work when I provide style attribute name along with the id of the element in parameter but I just want to pass the id of the element and should be able to get all the style attributes along with values.
function should be something like getStyleById(elementId);
PFB the code snippet so far:
var styleNode = [];
var styles;
var sty = x.style;
var len = sty.length;
for (var i = 0; i < len; i++)
{
styles = sty.item(i);
if (x.currentStyle) //IE for External/Global Styles
{
var a = x.currentStyle[styles];
styleNode.push(styles + ":" + a);
}
else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox,Chrome,Safari for External/Global Styles
{
var b = document.defaultView.getComputedStyle(x, "").getPropertyValue(styles);
styleNode.push(styles + ":" + b);
}
else //Works in Inline Styles only
{
var c = x.style[styles];
styleNode.push(styles + ":" + c);
}
}
Upvotes: 27
Views: 24388
Reputation: 49280
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
Upvotes: 0
Reputation: 349042
Use the following method:
CSSStyleDeclaration
object (getComputedStyle) to get each known property name. Use getPropertyValue
+ this name to get the value.getComputedStyle
for each iteration, but store it in a variable outside the loop.for ( name in object )
loop for currentStyle
.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;
}
Upvotes: 27