Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
139
rated 0 times [  144] [ 5]  / answers: 1 / hits: 61840  / 11 Years ago, thu, june 6, 2013, 12:00:00

How can I access a property from a CSS class by jQuery?
I have a CSS class like:



.highlight { 
color: red;
}


And I need to do a color animation on an object:



$(this).animate({
color: [color of highlight class]
}, 750);


So that I can change from red to blue (in the CSS) and my animation will work in accordance with my CSS.



One approach would be to place an invisible element with the highlight class and then get the color of the element to use in the animation, but I guess this is a very, very bad practice.



Any suggestions?


More From » jquery

 Answers
20

I wrote a small function that traverses the stylesheets on the document looking for the matched selector, then style.



There is one caveat, this will only work for style sheets defined with a style tag, or external sheets from the same domain.



If the sheet is known you can pass it in and save yourself from having to look in multiple sheets (faster and if you have colliding rules it's more exact).



I only tested on jsFiddle with some weak test cases, let me know if this works for you.



function getStyleRuleValue(style, selector, sheet) {
var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
for (var i = 0, l = sheets.length; i < l; i++) {
var sheet = sheets[i];
if( !sheet.cssRules ) { continue; }
for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
var rule = sheet.cssRules[j];
if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) {
return rule.style[style];
}
}
}
return null;
}


example usage:



var color = getStyleRuleValue('color', '.foo'); // searches all sheets for the first .foo rule and returns the set color style.

var color = getStyleRuleValue('color', '.foo', document.styleSheets[2]);


edit:



I neglected to take into consideration grouped rules. I changed the selector check to this:



if (rule.selectorText.split(',').indexOf(selector) !== -1) {


now it will check if any of the selectors in a grouped rules matches.


[#77780] Wednesday, June 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnyblaynes

Total Points: 667
Total Questions: 121
Total Answers: 102

Location: Anguilla
Member since Sat, Jan 23, 2021
3 Years ago
johnnyblaynes questions
;