Peter
Peter

Reputation: 11835

Read all CSS selectors using jQuery

What is the best way to read all CSS selectors from my CSS $("head > style:eq(0)").html(); ?

Upvotes: 1

Views: 89

Answers (1)

bobince
bobince

Reputation: 536389

It varies across browsers. jQuery doesn't help you here, because inspecting the stylesheet data is a quite an unusual thing to want to do, and older/niche browsers can't do it at all. Are you sure you need to inspect stylesheets? What are you aiming to do?

var sheet= document.styleSheets[0];
var rules= 'cssRules' in sheet? sheet.cssRules : sheet.rules;
for (var i= 0; i<rules.length; i++) {
    var rule= rules[i];
    var text= 'cssText' in rule? rule.cssText : rule.selectorText+' {'+rule.style.cssText+'}';
    alert(text);
}

cssRules and cssText are standard DOM Level 2 Style properties, rules and selectorText are for IE<9 compatibility. Note IE<9 will return recreated rules so you'll see eg. PADDING-BOTTOM: 0pt; PADDING-LEFT: 0pt; PADDING-RIGHT: 0pt; PADDING-TOP: 0pt if the original style you specified was padding: 0.

Upvotes: 3

Related Questions