04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11: DOM Levels 2 and 3<br />

function insertRule(sheet, selectorText, cssText, position){<br />

if (sheet.insertRule){<br />

sheet.insertRule(selectorText + “{“ + cssText + “}”, position);<br />

} else if (sheet.addRule){<br />

sheet.addRule(selectorText, cssText, position);<br />

}<br />

}<br />

This function can then be called in the following way:<br />

insertRule(document.styleSheets[0], “body”, “background-color: silver”, 0);<br />

Although adding rules in this way is possible, it quickly becomes burdensome when the number of rules<br />

to add is large. In that case, it ’ s better to use the dynamic style loading technique discussed in Chapter 10 .<br />

Opera prior to version 9.5 doesn ’ t always insert the new rule in the correct location.<br />

Unfortunately, there ’ s no complete workaround for these early Opera versions.<br />

Deleting Rules<br />

The DOM method for deleting rules for a style sheet is deleteRule() , which accepts a single<br />

argument: the index of the rule to remove. To remove the first rule in a style sheet, the following code<br />

can be used:<br />

sheet.deleteRule(0);<br />

//DOM method<br />

IE supports a method called removeRule() that is used in the same way, as shown here:<br />

sheet.removeRule(0);<br />

//IE only<br />

The following function handles deleting a rule in a cross - browser way. The first argument is the style<br />

sheet to act on, and the second is the index to delete, as shown in the following example:<br />

function deleteRule(sheet, index){<br />

if (sheet.deleteRule){<br />

sheet.deleteRule(index);<br />

} else if (sheet.removeRule){<br />

sheet.removeRule(index);<br />

}<br />

}<br />

This function can be used as follows:<br />

deleteRule(document.styleSheets[0], 0);<br />

As with adding rules, deleting rules is not a common practice in web development and should be used<br />

carefully because the cascading effect of CSS can be affected.<br />

335

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!