Working with the DOM Stylesheets Collection [con't]
deleteMedium() method deletes one media type at a time. Deleting
a medium not in the list, or that the browser doesn't understand, will
cause it to throw a 'Node not found' error. Deleting all media types from the
list will cause the media text to be empty, so it will once again be applied
to all media types:
You can preemptively avoid the 'Node not found' error by looping through
the listed media types using the
item() method and verifying that the
media type is in the list before deleting it:
The following function would add a new media type to all the style sheets in a page. It returns the number of additions that were made:
Accessing the Stylesheet Directly
styleSheetobject is through the tag that contains it. Once you obtain a reference to the
STYLEelement, you can reference the associated
styleSheetobject using the
sheetproperty of the element:
The CSS Rule object
Presumably, obtaining a reference to the a
styleSheet object is only
the first step. The real goal is to manipulate the rules contained therein.
The css rules are exposed via the
cssRules property in DOM compliant
browsers and the
rules property in Internet Explorer.
cssRules object contains five properties:
- cssText (not available in IE): returns the content of a css rule in its entirety, from the selector to the corresponding CSS declaration(s). A useful property to easily search within a rule, by looking at both the selector and attributes of a rule all at once.
- length: the number of rules within a style sheet.
- parentStyleSheet: the
styleSheetobject that contains the current rule.
- selectorText: returns the selector part of a rule.
- style: provides access to individual attributes defined
in the rule, similar to the
styleobject of inline styles.
The following example retrieves the rule for
<P> tags within the
first style sheet in the page:
The methods to add and delete rules from a style sheet depend on the browser you are coding for. Your choices are:
|Internet Explorer||DOM Compliant Browsers|
|addRule(selector, declaration, [index]): adds
a new rule to the style sheet, where the parameter
||insertRule(rule, index): Inserts a new rule
to the style sheet, where the parameter
|removeRule([index]): removes the first rule
of a style sheet. Enter an optional index (integer) to remove a specific
rule based on its position in the
||deleteRule(index): Removes a rule from the
style sheet based on its position in the