For example I might have some css stuff that looks like this:
.divType1 {
position: absolute;
width: 60px; height: 60px;
left: 400px; top: 100px;
border: 1px solid #89B;
z-index: 0;
}
Now within Javascript I want to gather div class divType1′ css attributes, but am provided only with the div class, so I can’t do something of form ( pseudo-code ):
selectDivWithClass( divType1 ).getCss(left).
I could hack something by instantiating a div with class divType1 and grab its css attributes, and then destroy it, but is there a better way?
The original question has some ambiguity, resulting in lots of good answers that will work in other settings. So here’s the restated one:
Using Javascript, how do I gather a subset of a div class’ css attributes specified by the maker in the stylesheet, so no browser defaults. Furthermore, assume only ‘plain-vanilla’ attributes will appear in the css. So stuff like width, height, not stuff like:
transition: width 2s;
-moz-transition: width 2s; /* Firefox 4 */
-webkit-transition: width 2s; /* Safari and Chrome */
-o-transition: width 2s; /* Opera */
I am given nothing but the class name, so I am not given a list of attributes I need to collect before hand.
Finally, the function ideally should return an object mapping style attribute to value.
In the scope of what I am trying to do, the problem is solved by @RobG’s answer below.
Inpsecting an element that has the rule applied to it won’t work unless you can filter out the effects of all other rules and default properties (which might be different in different browsers and be the same as a rule property in some but not others). That seems unlikely to be successful in more than one or two browsers in their default configurations.
To get the CSS rule text as text in a cross-browser fashion, use something like:
Note that this will return the actual text of the rule.
Also, there is a CSSValue property, but I am unsure of support.
Edit
If you are dealing only with the rules part and not the selector, you should be able to turn it into an object using something like:
You may want to trim the property names and values of leading and trailing spaces, but that should work. I’m no expert on CSS properties though, so the above may need some tweaking.
Note that if there is a trailing ‘;’ (which browsers seem to add if the original rule didn’t have one), the last member of
propswill be ” (empty string).One thing you absolutely can’t guarantee is the order that properties will be in, not that you can know what order
for..inwill return them in anyway. IE seems to returncssTextin its own order, Firefox seems to preserve the original order.