Get the rendered style of an element

I guess most of you, one time or another, has had the need to find out what style was actually rendered on an element. The easiest way to do this is through the style property followed by the specific value you’re looking for:


	var intPosLeft = document.getElementById("left").style.left;

However, this only works if the CSS has been applied inline on the element. As we all (or at least most of us) have realized, having inline styles isn’t a very good and efficient approach. So then we move all our CSS to an external file and suddenly the style property return no values when checking it.

What the hell happened?

The style property is reserved for inline styles (ridiculous, if you ask me), so you need to find another way to do it. Of course, then, there’s one standard way and one Microsoft way.

I have put together a function named getStyle (yes, the name is supposed to be funny) to solve this issue for you:

I’ve updated one line for IE per zcorpan’s suggestion. The previous code worked fine as well, it’s just a matter of personal preference when it comes to code syntax.


function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

It is then called, for instance, like this:


	getStyle(document.getElementById("container"), "font-size");

The first parameter is an object reference to the element you want to check, the second is the CSS name of the property you want to know the rendered value for.

Interesting to know is that specific values will return a value even if it was applied by shorthand in the CSS. For example, this will work just fine:


/* Element CSS*/
div#container{
	font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;	
}

var elementFontSize = getStyle(document.getElementById("container"), "font-size");

An other interesting thing is that Firefox, Opera and Safari will returned the actual pixels of a font size applied with em, while IE only return the value in em.

Web browser compatibility

This script has been tested to work in the following web browsers:

  • IE 5.5+
  • Firefox
  • Safari
  • Opera 8.5

The reason that it doesn’t work in IE 5.0 is having a function in the replace method as a second parameter. You might want to put this in a try...catch clause if you expect any users with that version, like this:


try{
	strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
		return p1.toUpperCase();
	});
	strValue = oElm.currentStyle[strCssRule];
}
catch(e){
	// Used to prevent an error in IE 5.0
}

 

Download the JavaScript file

Download the getStyle JavaScript file.

87 Comments

  • Kristin says:

    Smutt Robert (smutt – swedish for nice)

  • Tim Hofman says:

    I stumbled over this in one of my own projects. Like you said it is pretty ridiculous that the style property only works combined with inline stylerules.

    This function will sure come in handy, thanks!

  • It's not that ridiculous that .style only maps to inline styles — it's really just a shortcut to the style attribute.

    Granted, it would be mildly less ridiculous if getting the computed style wasn't so convoluted.

  • zcorpan says:

    Shouldn't <code>strValue = oElm.currentStyle[strCssRule];</code> work instead of using <code>eval()</code>?

  • Per Zimmerman says:

    Check out the FireFox extension CSSViewer, which does the same thing (at least some of it).

  • Thanks for the code! I agree with the other poster: try to eliminate the "eval" (blech!)

  • gRegor says:

    Similarly, the Firefox extension View Source Chart displays the rendered source (including styles after applied to elements) of the entire document in a neatly structured view. Highly recommended.

  • […]

    Satunnainen Björklund 24.4.2006 Elementin laskettu tyyli Robert Nyman: Get the rendered style of an element. Näppärää JavaScriptiä. […]

  • Robert Nyman says:

    Kristin, David,

    While I have heard that term, it doesn't have a nice ring to it in English… 🙂

    Tim,

    No problem, I hope it will be of use to you.

    Cameron,

    Logically, of course you're correct. But, like you say, it's probably because it's so tricky to get the computed style that I'm opposed to that approach, plus the fact that no one uses inline styles anyay, so then <code>style</code> becomes obsolete.

    zcorpan,

    Yes, that works too. Didn't think of it, but I like that syntax better, so I've updated the post and code per your suggestion.

    Patrick,

    Thanks! Code updated, although in general I don't regard <code>eval()</code> as inherently evil… 🙂

    Per, gRegor,

    Thanks for the information.

    Although, at least not to me, the purpose of this script isn't just to see what's rendered as general information, but to act on what value a certain style has got and then build on it in the current web page.

  • There's also that oddball 'float' css property, in IE it's 'elm.styleFloat' and in moz it's 'elm.cssFloat'.

    Might want to support that too.

  • Robert Nyman says:

    Andrew,

    That's very true, thanks for pointing that out.

    I don't think I'll incorporate it in this script because a) I want to keep the function as simple and light-weight as possible and b) I think it's something one rarely looks for thus the need isn't that big.

    However, it's very good to be aware of that difference.

  • Mislav says:

    This is exactly what Prototype library does with its Element.getStyle

  • Ash Searle says:

    Mislav,

    Not exactly… the code's similar, but prototype's getStyle is broken….

    prototype's getStyle function checks element.style first, assuming that if a specific property is set inline it will override anything set in a stylesheet – and they then avoid a potentially slow call to getComputedStyle. This can produce the wrong result, as !important properties take precedence over inline styles. Unless the inline style is also !important.

    If you've got a rule like this…

    <code>ul { display: block !important }</code>

    …and some HTML like…

    <code><ul style="display: inline">…</code>

    That list isn't going to be inline, and it still won't be inline even after using script to set <code>element.style.display = "block";</code>

    But, if you're really stubborn, you can counter-strike with !important in script too:

    <code>element.style.display = "block !important";</code>

    Now, Robert's getStyle doesn't have that issue. Let's assume that's by design…

  • Tobie Langel says:

    <blockquote cite="">An other interesting thing is that Firefox, Opera and Safari will returned the actual pixels of a font size applied with em, while IE only return the value in em.

    That is one of the most annoying differences between Gecko based browsers and Internet Explorer; it is of course related to the <code>getComputedStyle</code> and <code>currentStyle</code> functions which don't render the same thing at all. (As their names rightly suggest, <code>getComputedStyle</code> returns the styles as computed for display, while <code>currentStyle</code> returns the result of the cascade, before computation into pixels.)

    I don't think one function is better than the other. Actually, I would dream of having both of them available in either browser.

    For now, there is unfortunately no middle-ground (i.e. no <code>getComputedStyle</code> equivalent in IE, and no <code>currentStyle</code> equivalent in Firefox).

    So that's tough luck if you need a cross-browser solution on issues like font-sizes set in anything else than pixels…

  • Robert Nyman says:

    Mislav,

    I'm not sure what's in the Prototype library or how it works, but this is offerred just as a handy function and not a library replacement.

    Ash,

    Thanks for clearing that up.

    Tobie,

    Actually, I would dream of having both of them available in either browser.

    Me too… 🙂

  • Sammy says:

    Could this function be adapted to be a bookmarklet ? Something like: click bookmarklet to see which elements are floated, and which are positioned (by giving them a border or something). It would be great to quickly analyze existing websites and their layout techniques. Giving a border to tables or divs with a bookmarklet is one thing, but instantly seeing the kind of positioning that is used would be really cool. Any ideas ?

  • Robert Nyman says:

    Sammy,

    I guess that could be done, but for such usage tools like the Web Developer Toolbar extension for Firefox is much better.

  • setmajer says:

    I'm very late to the party here, but one could make this script work in IE5 by replacing the regex with:

    <code>while(-1 != (dashIndex = strCssRule.indexOf('-'))) {

    strCssRule= strCssRule.substring(0,dashIndex) + strCssRule.substring(dashIndex + 1, dashIndex + 2).toUpperCase() + strCssRule.substring(dashIndex + 2);

    }</code>

    Also, it is possible to calculate the pixel height of text by adding a dummy element with a single character inside to the desired location in the document, zeroing padding and borders, setting line-height to 1 and then getting the offsetHeight.

    I suspect one could write an ugly little kludge that would use that technique to normalise returned font sizes (or even line-heights) to pixels.

    Getting pixel values for borders, padding and so on would be considerably trickier, however.

  • Ess says:

    Thanks a lot for sharing this useful tip with us.

  • Juan says:

    Do you know how to actually calculate the pixel width of a style in IE for this example? If I don't set a 'width' on an object, FireFox and Safari return the proper pixel width, but IE returns 'auto'. Any way around it? Thanks!

  • Robert Nyman says:

    setmajer,

    Thanks for the suggestions. And yes, dummy elements are always good to test things like that.

    Inge,

    Thank you for the added functionality.

    Ess,

    No problem! 🙂

    Juan,

    To begin with, the idea is only to find out the rendered value when some CSS is actually applied. However, to make that work in IE, you then need to check for the element's <code>offsetWidth</code>, like this:

    <code>var intWidth = document.getElementById("juans-element").offsetWidth</code>.

  • […] A very handy way to find out the rendered CSS styles on an element, Described in detail in Get the rendered style of an element. Support for Array.push in I […]

  • […] F、IE、Opera、Safari下同时兼容的做法步骤: 1、定义函数getStyle – 参考 […]

  • Jonathan Leech says:

    What would be even more awesome is if this supported the css shorthand properties; e.g. for border. It would be very convenient to be able to just call getStyle(elem, "border") and it would return "2px solid green" or whatever. Instead you've got to call getStyle() on {border-left-, border-top-, border-right-, border-bottom-} * {color, style, width}. Even if it wasn't smart and didn't build the most efficient shorthand it would be very useful.

  • Robert Nyman says:

    Jonathan,

    I agree that that would be good. As it is now, it just returns what the web browsers give you. However, it wpuld be a nice way to extend it, although it won't be done just at this moment… 🙂

  • Olle Lundberg says:

    Webkit has a bug in the way it handles the string passed to getPropertyValue() according to the spec the string passed, is case insenstive. I.e width==Width.

    I have created at test case and reported it to webkit.

    A workaround for now is making the strCssRule lowercase.

    <code>

    function getStyle(oElm, strCssRule){

    var strValue = "";

    strCssRule=strCssRule.toLowerCase();

    if(document.defaultView && document.defaultView.getComputedStyle){

    strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);

    }

    else if(oElm.currentStyle){

    strCssRule = strCssRule.replace(/-(w)/g, function (strMatch, p1){

    return p1.toUpperCase();

    });

    strValue = oElm.currentStyle[strCssRule];

    }

    return strValue;

    }

    </code>

  • Bernie says:

    This function doesn't work in Firefox with "backgroundImage".

  • […] computed styles in Javascript Robert Nyman has written a useful blog entry on this, you might want to read it as well. The getStyle() function is based on his, with one […]

  • Bereczki Andrei says:

    Hi, nice script, i was using something similar but this seems more browser friendly. I have a suggestion and 1 bug for you to fix (if you want of course):

    1. Stripping away the 'px' from the return values would be nice to be able to use it in mathematical operation

    i did it the following way:

    if(strValue.indexOf("px") != -1){ //stripping away 'px'

    strValue = parseInt( strValue.slice(0, strValue.indexOf("px")) );

    }

    return strValue;

    2. There seems to be a bug with getting the border values. Even if the border is not set in css, i still get a 0px (medium in IE) and #000000 color for that border … is this normal?

    Have a great day! 🙂

  • Bereczki Andrei says:

    o, forgot to mention, if i set the color property in css, the border color changes to that color, even if not set … annoying

  • Robert Nyman says:

    Olle,

    Thanks for the info!

    Bernie,

    You need to send in <code>background-image</code> to the function, like in CSS. Alternatively, you can send in just <code>background</code>

    Andrei,

    Thank you!

    1. It's a good suggestion, but it was a deliberate choice to have it return the unit as well, in case there are more than one unit in use.

    2. The problem is that what is returned is the default value in the web browser, which can differ quite a lot between different web browsers.

  • iain says:

    Thanks for this… exactly what I needed.

    You absolute legend

  • Robert Nyman says:

    iain,

    I'm glad it helped! 🙂

  • mihai copae says:

    If you want to parse the entire css for document u can use this:

    <code>

    n=document.styleSheets[0].cssRules.length

    css_rules=document.styleSheets[0].cssRules

    i=0;

    while(i<n){

    console.log(css_rules[i].cssText)

    i++;

    }

    </code>

  • Picmauri says:

    I've tried the script on my project….with Firefox works Fine!

    With Explorer 7 does not works!!!

    …..try{

    strCssRule = strCssRule.replace(/-(w)/g, function (strMatch, p1){

    return p1.toUpperCase();

    });

    strValue = oElm.currentStyle[strCssRule];

    }

    catch(e){

    // Used to prevent an error in IE 5.0

    }

    ….The line "// Used to prevent an error in IE 5.0" on statement catch Why is blank?

    Have i to write some code in that line?

  • Robert Nyman says:

    Picmauri,

    The script should work in IE 7, so make sure you don't have any other error in there. The commented out line is only there to handle any potential error, so you can alert the value of e, to see what error you get.

  • picmauri says:

    Hi Robert,

    Now is work fine.

    The problem was a mismatch on the background-color value….the color value of an element with firefox is expressed with rgb (xxx,xxx,xxx) , while with IE7 the same value is expressed with #xxxxxx. However i had some error with another script.

    TNX

    and sorry for my english….I'm from Italy!

  • Robert Nyman says:

    picmauri,

    No problem at all. I'm glad to hear that it works for you now!

  • Mario says:

    For top and left it returns auto which is not very useful.

  • Andy says:

    Wow, this is an awesome tip! Thanks, that helped me solve a huge problem that I had been trying to figure out for a while, thanks!

  • Gunnar says:

    You saved my day!

  • Troy III says:

    Reading this and that and those and what not, I come to one and only conclusion that is growing stronger and stronger everyday more.

    That IE is a Browser – FX is a ridicule – while W3C is a godamn Dogma.

  • […] July 07, 2008 /* Gets the rendered style of an element. * Credit and thanks to: Robert’s Talk * Get the rendered style of an element – Robert’s talk – Web development and Internet trends * * Example usage: getStyle(document.getElementById(“container”), “font-size”); */ function […]

  • […] Geist’s Blog /* Gets the rendered style of an element. * Credit and thanks to: Robert’s Talk * Get the rendered style of an element – Robert’s talk – Web development and Internet trends * * Example usage: getStyle(document.getElementById(“container”), “font-size”); */ function […]

  • Thank you! element.style.height didn't work out for me and this helps! Thanks!

  • […] A continuación se muestra una función compatible con todos los navegadores, creada por el programador Robert Nyman y publicada en su blog personal: […]

  • Ariden says:

    Thanks for this tuto, this is exactly what I needed.

    Good continuation

  • […] aquellos que quieran hacer modificaciones al estilo de su página de esta forma, la entrada original con el método adjunto en un fichero está en el blog de Robert […]

  • Rik says:

    I can't get this to work in Firefox 3 but all I've done is copied and pasted the code. I've put an alert in at the beginning and end of the function and I get the first one but not the second one. Any ideas?

  • Robert Nyman says:

    Rik,

    Check if you get any JavaScript errors, and see what it states.

  • […] el blog de Robert Nyman encuentro el siguiente […]

  • Gerardo says:

    I had to use the getter to get the style, getPropertyValue returned an empty string:

    <code>str = "strValue = document.defaultView.getComputedStyle(oElm, '')."+strCssRule;

    eval(str);</code>

    This happend on Firefox 3 under Ubuntu.

    Found this code very useful.

  • Leto 58 says:

    Hi,
    Your function works as expected, but when I use it to test visibility of some elements for example, it returns “inherit”, while I expect a useful value.
    What I would call a “rendered style” for visibility is either “visible” or “hidden”, and surely not “inherit”. 🙂

    Is there any smart function to get the “actual rendered style”, or must I test each parent recursively until I find one that has not “inherit” for the given style ?

    God job anyway
    Regards,
    Leto

  • Robert Nyman says:

    Leto 58,

    Unfortunately, not out of the box. Most JavaScript libraries struggle with this too, but some of them have nice solutions. If you don’t want that, testing the code recursively is, as far as I know, the only option.

  • '+' says:

    […] Robert Nyman […]

  • […] Get the rendered style of an element […]

  • damvaz says:

    hi!
    How do I read all the css properties of an element?
    (so then reapplied to the page)
    css properties that were defined in a “style” of course.

    In other words, I want a function to reset the page after I’ve changed some way of using the DOM element. Thank you.

    PS: I suppose it should work with nested loops.

  • Robert Nyman says:

    damvaz,

    There's no short solution to show the code here, but yes, just looping over style properties would do.

    Alternatively, you could use the Inline Code Finder Firefox extension.

  • Ghislain says:

    Wow great !

    I was looking for this regexpr for a while and I didn't know it was possible to use an anonymous function to process the found string. good work !

  • Justin says:

    Do you know if there is a way to retrieve the :hover attributes in firefox? I know you can do this in I.E. but the last I checked it was not possible in firefox.

  • Robert Nyman says:

    Ghislain,

    You're welcome!

    Justin,

    Sorry, no, not that I know of.

  • gprs says:

    Dude, i just wanted to thank you. i've spent the last several hours trying to find a way to get style details that works across browsers.

    wicked. Now i can get on with my life 🙂

  • Robert Nyman says:

    gprs,

    Glad it was of use!

  • […] in to an HTML file with only inline CCS style attributes ?Edit: Any Javascript solution ( ie: http://www.robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ ) ? With jQuery ? […]

  • I’m using this great script but stumbled upon a annoying error:
    IE8 and below return “auto” instead of the computedStyle when you try to retrieve the width or height from an element with an unspecified width or height.

    I added this to solve the problem:

    if(strValue == "auto"){
       if(strCssRule == "width"){
          strValue = oElm.offsetWidth;
       }
       if(strCssRule == "height"){
          strValue = oElm.offsetHeight;
       }
    }

  • Robert Nyman says:

    Jan Van Lysebettens,

    I haven’t tested, but thanks for the tip!

  • marcel says:

    nice function dude.
    i think it’s strange the style of a HTML Element is empty in the DOM.
    but i’m probably missing something here.

  • Darrell Thompson says:

    Thank you so much for this function. Prior to this I could not read the initial style values defined in my ccs file although, once set by any function, they were readable. Your work has saved me from making ASS-U-MEs. Thanks, again.

  • Robert Nyman says:

    marcel, Darrell,

    Thanks, glad you like it!

  • peter says:

    this always gives me runtime exceptions in firefox when i do it like this:

    var divs = document.getElementsByTagName(‘div’);
    var count = 0;

    for(i in divs)
    {
    if(count == 50) break;

    console.log(getStyle(divs[i],’background-color’));
    count++;
    }

  • Robert Nyman says:

    peter,

    Don’t know why. Try some try…catch and see which div throws the error, and why.

  • […] link to jQuery within the bookmarklet and use jQuery to read the styles properly, or you could include a function to get the true styles. But for the purpose of this simple bookmarklet, I don’t think it’s […]

  • shallker says:


    function getStyleProp(obj, prop) {
    // allBro( ~IE9- )
    if ( window.getComputedStyle ) {
    var objCompStyle = window.getComputedStyle(obj, "");
    return objCompStyle[prop];
    }
    // Bro( IE9- )
    else {
    return obj.currentStyle[prop];
    }
    }

    —————————————
    I have a function can do this job too, hope it can help you!

  • Robert Nyman says:

    shallker,

    Right, but currentStyle doesn’t support the same format, so you need to change that – like the code above in the blog post.

  • Geoff says:

    Excellent post. Very helpful, thank you.

    (“The standard way, and the IE way.” Funny. 🙂

    Is this functionality now available naitively (in the DOM)? Or is this method still necessary?

    Thanks again.

  • Robert Nyman says:

    Geoff,

    For older versions of IE, you will still need this. Depends on your level of web browser support.

  • Chris says:

    I’ve adapted your code to return a list of value-pair. In some situations this function may be a lot more useful:
    function GetComputedStyle(element)
    {
    var css={},i,v,style;
    if(document.defaultView && document.defaultView.getComputedStyle)//the Standard way
    {
    style=document.defaultView.getComputedStyle(element);
    for(i=0;style[i];i++)
    if((v=style.getPropertyValue(style[i])))
    css[style[i]]=v;
    }
    else if(element.currentStyle)//and, of course, the IE way
    {
    for(i in element.currentStyle)
    if((v=element.currentStyle[i]))
    css[i]=v;
    }
    return css;
    }

  • Robert Nyman says:

    Chris,

    Thanks for sharing!

  • Bob says:

    I knew I could find what I was looking for here. This post may be form 2006, but what I needed was in the second-to-last comment from 9/9/2011. I think that comment deserves to be highlighted.

  • Robert Nyman says:

    Bob,

    Good to hear that you find some use for it!

  • Simon says:

    You really helped me a lot.
    Thank you so much.
    Your know-how is amazing.
    I’ve been struggling for days until I read this.
    Thank you so much for sharing your knowledge.

  • DutchSpeed says:

    It’s seems not working with document.getElementsByClassName.

    See here for an example: http://jsfiddle.net/GMLqW/1/

    I get these errors:
    with Mozilla Firefox:
    NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument arg 0 [nsIDOMWindow.getComputedStyle] @ http://fiddle.jshell.net/GMLqW/1/show/:32

    with Google Chrome
    Uncaught TypeError: Cannot call method ‘getPropertyValue’ of null fiddle.jshell.net:32

    with Internet Explorer:
    SCRIPT16386: No such interface supported.

    and with Opera:
    Unhandled Error: WRONG_ARGUMENTS_ERR

    However, it handles document.getElementById perfectly,
    see here: http://jsfiddle.net/GMLqW/

    Somebody has an answer?

    Thanks in advance.

  • Robert Nyman says:

    Simon,

    Thank you!

    DutchSpeed,

    It’s because the function only supports one element, not an array, as the first parameter. You need to have a loop iterating over elements and calling the function for each element to make it work (or tweak the function itself to accept an array).

  • […] will help you   Using javascript Get the rendered style of an element[^] answerThanks for your question. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.