1
.test
{
 color:Red;
 width: 100px;
}

   var r = document.styleSheets[index].rules;   

   r[0].selectorText => Here we get ".test";

Now i want to get access of all .test properties (in this case color and width) in an array and its values ( in this case Red & 100px ).How can i do this?

2 Answers 2

3

You want the .cssText of the CSSStyleRule. (You can find this yourself with console.log(document.styleSheets[2]) on this page and diving through the items in the console of Chrome or Firebug.)

Also note that while .rules works in some browsers, the DOM Level 2 CSS binding is .cssRules.

Edit: If you need access to individual styles, then use the .style property. Again, you could see if this you used the developer console.

var sheet = document.styleSheets[2];
var rules = sheet.cssRules[1];
console.log( rules ); // Lots of properties
console.log( Object.keys(rules) );
// ["parentRule", "cssText", "type", "selectorText", "style", "parentStyleSheet"]
console.log( rules.style.display ); // "none"

If you want to see just the styles that are applied in this rule, you'll have to either iterate through the properties of the .style collection (which includes properties that were not explicitly set) and check for empty values, or else you'll need to parse the cssText yourself.

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

6 Comments

Doesn't .cssText only apply to embedded css?
@Mathachew Not sure what you mean. On this page document.styleSheets[2].cssRules[1].cssText #=> "#adzerk2, #adzerk2 + div { display: none !important; }"
thanks for ans but this return all (just like innerhtml of any element) but i want it individualy like a array, like array[0] = color, array[1] = width
@Phrogz I had this mixed up with something I was working on the other night and .cssText wasn't reliable. However, I wasn't aware of document.styleSheets and was instead trying to pull straight from an element with mixed results between IE and Chrome. Edit: this is what I was referring to: jsfiddle.net/Ur474/1
How can i iterate all properties of .style collection
|
-1

jQuery makes this easy.

$('.test').each(function(){
    var curColor = $(this).css('color');
    // etc
});

6 Comments

That would fail as this is the DOM element and not a jQuery element thus css is not defined.
It would work just fine. this is a jQuery element in the current scope.
No it isn't just look at the error in the console on this jsfiddle.net/bMS7D/1
api.jquery.com/each "More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element."
but .test is in css file and we are reading it from there r[0].seletorText = ".test"
|

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.