Cover by David Flanagan

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Scripting Stylesheets

So far, we’ve seen how to set and query the CSS styles and classes of individual elements. It is also possible to script CSS stylesheets themselves. This is not commonly done, but it can occasionally be useful and this section sketches out the technique.

When scripting stylesheets, there are two kinds of objects you may need to work with. The first kind are the Element objects that represent <style> and <link> elements that contain or reference your stylesheets. These are regular document elements and if you give them id attributes, you can select them with document.getElementById(). The second kind of object is a CSSStyleSheet object that represents the stylesheet itself. The document.styleSheets property is a read-only array-like object containing CSSStyleSheet objects that represent the stylesheets associated with the document. If you set the title attribute of the <style> or <link> element that defines or references the stylesheet, that title will be available as the title property of the corresponding CSSStyleSheet object.

The subsections that follow explain what you can do with these style and link elements and stylesheet objects.

Enabling and Disabling Stylesheets

The simplest stylesheet scripting technique is also the most portable and robust. <style> elements, <link> elements, and CSSStyleSheet objects all define a disabled property that you can query and set in JavaScript. As its name implies, if the disabled property is true, then the stylesheet is disabled ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required