views:

83

answers:

2

Hi,

For a DOM element, how to I get all styles specified in css for a particular element? Is it a case of iterating over all css style names?

Or is there a more elegant way? How does Firebug do it?

Thanks

+2  A: 

For a DOM element, how to I get all styles specified in css for a particular element? Is it a case of iterating over all css style names?

Yes, it is.

Or is there a more elegant way?

I don't know about more elegant (elegance is pretty high on the subjective scale), but it would certainly be shorter and sweeter if you made use of a library such as jQuery, here's a solution someone coded to answer another question:

How Can I Get List Of All Element CSS Attributes with jQuery?

How does Firebug do it?

I have no idea.

karim79
A: 

You can iterate through all of the CSS styles for an element like this:

var myElement = document.getElementById('someId');
var myElementStyle = myElement.style;

for(var i in myElementStyle){
    // if it's not a number-index, print it out.
    if(/^[\d]+/.exec(i) == null){
        console.log("Style %s = %s", i, myElementStyle[i]);
        /*
         * Do other stuff here...
         */
    }
}
JasonWyatt
Hi - thanks for the suggestion - however myElementStyle[i] appears always to be null. My styles are set from external css, and not inline
Richard
Make sure you wait to run this code until after the document loads..
JasonWyatt
This only works for inline styles.
syockit