0

If I have a style tag on my page with css in it and I write the following javascript I will get the css text of all style tags.

//compatibility: all
$("style").each(function () {
    alert($(this).text());
});

I want to get the same text from all link element css files, like the following script.

//compatibility: IE Only
$("link").each(function(){
    alert(this.sheet.cssText);
});

Is there a cross modern browser friendly version of the above script?

2
  • document.styleSheets. Commented Sep 6, 2014 at 8:13
  • document.styleSheets.cssText is IE only also. is there another way of getting it via document.styleSheets? Commented Sep 6, 2014 at 8:44

2 Answers 2

1

Another way to access a CSS rule without actually accessing the stylesheet is to create an element, apply a rule to it and then access its properties with jQuery. Something like this:

var NewElement = $('.SomeClass');
var TheHeight = NewElement.prop('height');

Not sure if this would help but it's an idea. What are you trying to do anyway?

Edit:

var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;

rules[0].style.color = 'red';

This is from the answer here I added a jsFiddle Note that you must select the correct stylesheet index.

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

5 Comments

no, this doesn't help. I want to look for a token in the css text and create a new dynamic style based on it. for example: I want to create a new style based on a dynamic color code token. div{color:#COLOR1CODE#}. this is the concept anyway.
I don't understand this: "I want to create a new style based on a dynamic color code token."
i want to replace this css div{color:#COLOR1CODE#} with this div{color:red}
ok, now I understand better. Take a look at this link hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript
thanks for this but this is an IE only (and maybe firefox). i'm looking for a cross browser solution.
0

The only possible solution is to use AJAX:

$("link").each(function(){
    $.get(this.href, function(css){
        alert(css);
    });
});

Or you can use document.styleSheets

You can iterate over the style sheets:

var styleSheets = document.styleSheets;
for(var i = 0; i < styleSheets.length; i++){
    alert(styleSheets[i].cssRules)
}

3 Comments

I don't think I can get external css file contents with the ajax method and iterating over the styleSheet to get the cssRules or cssText is IE only. I'm looking for a cross browser method.
@user3693957 Why shouldn't the ajax method work in IE?
you cannot make an ajax request to an external resource. i.e. it can't be from a different domain.

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.