limc
limc

Reputation: 40176

Getting CSS file by ID to manipulate the properties

I have the following snippet that overwrites certain CSS properties:-

var styleSheet  = document.styleSheets[2]; // refers to the 3rd stylesheet

// Mozilla
if (styleSheet.cssRules) {
    var cssRule     = styleSheet.cssRules;

    // ... do something
}
// IE
else {
    var cssRule     = styleSheet.rules;

    // ... do something
}

This code works, but I don't like the fact that I'm referencing the stylesheet using document.styleSheets[2] because it is brittle. So, I assigned an id to the link tag, hoping that I can use JQuery to easily get that stylesheet by id. However, I'm not sure how to cast the returned object from JQuery into a CSSStyleSheet object so that I can assign it to styleSheet variable.

// I want to change this...
var styleSheet  = document.styleSheets[2]; // [object CSSStyleSheet]

// ... to something like this...
var styleSheet  = $("link#layout"); // not right because it is a [object Object]

Any clue? Thanks.

UPDATE

Per @TJ's suggestion, after futzing around, I think I might go with title instead of href... at least for now until I find any incompatibilities next time. Right now, this works in FF, IE, Safari and Chrome.

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

    if (document.styleSheets[i].title == "layout-overwrite") {
        // Mozilla
        if (styleSheet.cssRules) {
            var cssRule = styleSheet.cssRules;
            // .. do something
        }
        // IE
        else {
            var cssRule = styleSheet.rules;
            // .. do something
        }
    }
}

Upvotes: 3

Views: 1519

Answers (2)

denov
denov

Reputation: 12716

native js assuming your link tag as the ID of 'css'

document.querySelectorAll('link#css')[0].sheet;

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075189

The object you'll get back for that id will be the link DOM element, not the stylesheet.

As far as I know, there's no way to assign a name to a stylesheet and then look it up by that name. Instead, you'll need to define a "marker rule" (unless you already have a nice unique rule you can look for), loop through the style sheet objects, and look for that rule to determine that you've found the right one.

Edit: Both MDC and MSDN say there's an href property on their CSSStyleSheet object / styleSheet object, which would be even better than a marker rule.

Edit 2: And it (the href) seems to work in IE, FF, Chrome, and Opera, although I'm getting duplicate entries for the specific stylesheet I tested with: http://jsbin.com/edaga3/2 (Off-topic: Also note that if you load a stylesheet from a different origin, your browser may prevent access to the rules.)

Upvotes: 3

Related Questions