PDA

View Full Version : Accessing a styleSheets object via ID attribute?


WA
04-02-2003, 07:46 AM
Hi:
Is there a way to access a particular style sheet on the page using something other than its index number, such as the ID attribute? Lets say I have a stylesheet as follows:

<style type="text/css" id="mysheet">
body{
color:blue;
}
</style>

To access the above stylesheet, I figured I could use:

document.styleSheets["mysheet"]

though this technique seems to only work in IE and not NS6+. I wish to access it by ID since using its index number is not always reliable.

Thanks.

liorean
04-02-2003, 08:31 AM
Why don't you simply use document.getElementById, then?

The styleSheets collection uses W3C DOM2 CSS in moz and saf/konq, in between on iem, and ie proprietary in iew, which means there's no de facto standard way of handling it. Not to speak of, op7 and iCab supports getElementsById but not styleSheets.

WA
04-02-2003, 08:48 AM
Hi liorean:
Thanks. I've tried using document.getElementById() instead, though that didn't quite work in accessing the individual rules of the stylesheet. If I recall correctly while reading a book, using document.getElementById on a stylesheet object limits greatly what can in turn be accessed.

For example:

//this works (contains blue)
var test=document.styleSheets[0].cssRules[0].style.color

//this DOESNT:
var test=document.getElementById("mysheet").cssRules[0].style.color

It has to do with accessing the actual style sheet's object and not, respectively, I think.

brothercake
04-02-2003, 08:55 AM
I don't know if you care about this - but if you give a stylesheet <link> an ID then netscape 4 won't apply any of its rules, as if it weren't there at all.

I've found a good way to identify stylesheets is to give them a "title" attribute, and then iterate through getElementsByTagName("link") to find it.

WA
04-02-2003, 09:11 AM
Thanks Cake. The title attribute was useful, since apparently looking up "id" instead doesn't work.

I might just use the ancient document.write() and conditionally write out what I need, since between all the browser inconsistencies and incompatibility, it's becoming too much lol.

liorean
04-02-2003, 09:23 AM
var stylesheet=elm.sheet||elm.styleSheet||null;

W3C LinkStyle interface (http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/stylesheets.html#StyleSheets-extensions-h2)
In ie, you have to use the styleSheet object (http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/obj_stylesheet.asp) instead.

brothercake
04-02-2003, 06:41 PM
BTW - I once wanted to change the styles of all instances of an element, and jkd pointed me towards DOM 2 CSS to acheive this (http://codingforums.com/showthread.php?s=&threadid=14259)

Very cool .. but you know what ... it turned out to be slower than a getElementsByTagName iterator ...