3

How can i print the value of style attribute of an html element using javascript. I can get a specific style property value using document.getElementById('myId').style.property, where property is something like width, height etc.

However, how can I get the entire list of styles for an element?

1
  • If you want the value of an element's style attribute (i.e. the "inline" style) then the only way is getAttribute (which is buggy in some browsers so not very reliable). However, if you want values of the various properties of an HTML element's style object, the answers below might be helpful. Commented Sep 7, 2011 at 1:30

4 Answers 4

2

document.getElementById('myId').style.cssText as a String, or document.getElementById('myId').style as an Object.

Edit:

As far as I can tell, this returns the "actual", inline style. On the element <a id='myId' style='font-size:inherit;'>, document.getElementById('myId').style.cssText should return "font-size:inherit;". If that is not what you want, try document.defaultView.getComputedStyle or document.getElementById('myId').currentStyle (the first one is all except IE, the second one is IE only). See here for more on computed vs. cascaded styles.

Sign up to request clarification or add additional context in comments.

Comments

2
<div id="x" style="font-size:15px">a</div>
<script type="text/javascript">
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;
}

// get what style rule you want
alert(getStyle(document.getElementById('x'), 'font-size'));
</script>

1 Comment

Is document.defaultView supported in IE 9
2

Oh srsly... it's as easy as

element.style.cssText

and it's cross browser

http://jsfiddle.net/4F2RQ/

Comments

1

This should do a dump of the object: Here's an Example

EDIT: Its a little weird:

for (var prop in styles) {
    console.log(styles[prop], styles[styles[prop]]);
}

1 Comment

I thought the same thing; but unfortunately, that does not work.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.