user3693957
user3693957

Reputation: 709

How can I get the css file text via javascript?

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?

Upvotes: 0

Views: 2461

Answers (2)

frenchie
frenchie

Reputation: 51937

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.

Upvotes: 1

idmean
idmean

Reputation: 14865

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)
}

Upvotes: 0

Related Questions