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);
    }
}
4
  • I don't think you mentioned what's not working
    – Liviu T.
    Feb 24, 2012 at 12:38
  • 2
    Check this answer Feb 24, 2012 at 12:39
  • Perhaps this will help - stackoverflow.com/questions/5509830/… Feb 24, 2012 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. Feb 24, 2012 at 13:21

2 Answers 2

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;
}
10
  • 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 <p id="firstId" style="background-color:#aaaccc; color:red;">FirstId</p>, 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...... Feb 25, 2012 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<style.length;i++)styleNode.push(style[i]+':'+style.getPropertyValue(style[i]));return styleNode}.
    – Rob W
    Feb 25, 2012 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, 2013 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 1, 2013 at 7: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, 2016 at 15:35
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

1
  • not completely clear if how I can apply this to a specific element with id for example. Jun 4, 2021 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.