Changing external style
sheets using the DOM
Most of us are familiar with manipulating an element's inline style by
accessing its "style" object. There are times however, that you may find it
necessary to escalate the issue, and talk directly with the boss upstairs
that's the external style sheet on the page. Modifying an external style
sheet (style or link tag) is extremely powerful, yet should be noted is less
efficient and straightforward than going the route of dynamic inline styles.
With that declaration, lets begin!
Key to the gate: the styleSheet object
The styleSheet object of the document contains all the
external style sheets on the page, either defined using the <style> or
<link rel="stylesheet"> tag: This is how we access external stylesheets in
the DOM. For example:
document.styleSheets[0] //access the first external style sheet on the page
document.styleSheets.length //returns the total # of external style sheets
Referencing a particular external style sheet on the page
Now, you may be wondering, "So how do I pick out and
reference a specific stylesheet out of numerous on the page? Since the
stylesheet[] array only supports reference by position, we can use a for
loop and scoop out the one we want. One way is to assign a title attribute
to the style sheet of interest (inside its <style> tag) for the purpose of
identifying it:
for (i=0; i<document.styleSheets.length; i++){
if (document.styleSheets[i].title=="Blue style") //if style sheet is titled "Blue style"
mycss=document.styleSheets[i] //mycss now contains the style sheet we're looking for
break;
}
Here I give the style sheet I wish to access on the page a
title attribute of "Blue style", so our script can easily pick it out from a
lineup.
It's time to look at the styleSheet object in detail now.
|