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?

Wilfredo P
  • 4,070
  • 28
  • 46
user3693957
  • 669
  • 1
  • 5
  • 6

2 Answers2

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.

Community
  • 1
  • 1
frenchie
  • 51,731
  • 109
  • 304
  • 510
  • 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. – user3693957 Sep 06 '14 at 09:11
  • I don't understand this: "I want to create a new style based on a dynamic color code token." – frenchie Sep 06 '14 at 10:19
  • i want to replace this css div{color:#COLOR1CODE#} with this div{color:red} – user3693957 Sep 07 '14 at 04:41
  • ok, now I understand better. Take a look at this link http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript – frenchie Sep 08 '14 at 11:21
  • thanks for this but this is an IE only (and maybe firefox). i'm looking for a cross browser solution. – user3693957 Sep 09 '14 at 06:05
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)
}
idmean
  • 14,540
  • 9
  • 54
  • 83
  • 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 Sep 06 '14 at 08:46
  • @user3693957 Why shouldn't the ajax method work in IE? – idmean Sep 06 '14 at 09:14
  • you cannot make an ajax request to an external resource. i.e. it can't be from a different domain. – user3693957 Sep 07 '14 at 04:54