1

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

1 Answer 1

3

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.

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

Comments

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.