27

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);
    }
}
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
manishekhawat
  • 699
  • 3
  • 12
  • 18
  • I don't think you mentioned what's not working – Liviu T. Feb 24 '12 at 12:38
  • 2
    Check [this answer](http://stackoverflow.com/questions/2952667/find-all-css-rules-that-apply-to-an-element) – Alexander Pavlov Feb 24 '12 at 12:39
  • Perhaps this will help - http://stackoverflow.com/questions/5509830/is-it-possible-to-loop-through-the-style-attributes-of-a-div-with-javascript-or – Sean Carruthers Feb 24 '12 at 12:50
  • @LiviuT. 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. – manishekhawat Feb 24 '12 at 13:21

2 Answers2

27

Use the following method:

  • Loop through the indexes of the CSSStyleDeclaration object (getComputedStyle) to get each known property name. Use getPropertyValue + this name to get the value.
    Code optimalization: Do not use getComputedStyle for each iteration, but store it in a variable outside the loop.
  • Use an ordinary for ( name in object ) loop for currentStyle.
  • 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;
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    thanks a lot :) ... it worked great ... but only thing is I had given only 2 CSS style properties to the element while the value returned by this function contains a lot of CSS properties. like in this element

    FirstId

    , while returned value from the function contains ..................................................background-attachment:scroll,background-clip:border-box,background-color:rgb(170, 172, 204),background-image:none,background-origin:padding-box etc......
    – manishekhawat Feb 25 '12 at 17:55
  • 1
    @manishekhawat Do you want to *only* get **inline** styles (without stylesheet styles)? Then you should only use the code in the `else` block: `function getAllStyles(elem){if(!elem)return [];for(var styleNode=[],style=elem.style,i=0;i – Rob W Feb 25 '12 at 18:20
  • 1
    This code is awesome! Is there a way to get just the styles applied by a stylesheet or particular stylesheet? Similar to chrome's developer tools css style breakdown. – DyeA Apr 30 '13 at 23:27
  • Loop through all style style sheets and test every selector using matches / matchesSelector. The implementation is non-trivial and deserves an own question. Especially if you want to know which style is active. – Rob W May 01 '13 at 07:02
  • 1
    There is an error in your code in the last line: style[style[i]] will return "undefined" because style[i] returns "background-image" but it must be "backgroundImage" instead! – Elmue Jan 13 '16 at 15:35
  • @Elmue The last one works for me in Firefox 43 and Chrome 47. It'd be nice if you mention where it does not work. – Rob W Jan 13 '16 at 15:47
  • Obviously you will not notice the error if your code does not enter into the last "else". Execute only the last "else" block which says "ancient browser". It is useless because it does not work. – Elmue Jan 13 '16 at 15:54
  • @Elmue I tried to verify your statement by typing `document.body.style['background-color']` in the console, which returned a string. From that I concluded that it is working fine in Chrome and Firefox. If you rant about something not working, state which environment you've tested it in. – Rob W Jan 13 '16 at 15:56
  • I tested on Firefox. And apart from that; Your second block (else) is also wrong. You are using a non-existing variable 'currentStyle'. It seems you never really tested your code. Correct would be "for (var name in style)" instead of "for (var name in currentStyle)" and "style[name]" instead of "currentStyle[name]" – Elmue Jan 13 '16 at 15:59
  • @Elmue Thanks for the last remark, I fixed the typo. The comment about dashes vs camelCased properties still stands though: In Firefox 43, the "ancient browsers" part works for me. – Rob W Jan 13 '16 at 16:05
0

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

GorvGoyl
  • 42,508
  • 29
  • 229
  • 225