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 ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.