Removing Stylesheet Rules

01/13/2014, Mon
Categories: #JavaScript

Off with the Rule

Most of the time, css rules are overridden to get a different style, but some rules need to be outright removed. For example, if a hover effect is in place when javascript is disabled, but the rule might interfere with the javascript code when javascript is enabled. This might happen when using a jQuery plugin for menu creation or text effect.

The following code will demonstrate the removal of a :hover selector from a 'p' tag.

<!-- Example Layout -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Removing Stylesheet Rules</title>
    <link id="mainStyles" href="mainStyles.css" rel="stylesheet" />
    <script src="RemovingStyleSheetRules.js"></script>
  </head>

  <body>
    <p id="paragraph-is-orange-when-hover">
      This paragraph should be still be black when hover over.
    </p>
  </body>
</html>
/* mainStyles */

#paragraph-is-orange-when-hover:hover {
  color: orange;
}
// RemovingStyleSheetRules.js

// Retrieve sheet from css dom element
var mainStylesHtml = document.getElementById("mainStyles"),
  mainStyles;

if (mainStylesHtml.sheet) {
  mainStyles = mainStylesHtml.sheet;
} else if (mainStylesHtml.styleSheet) {
  mainStyles = mainStylesHtml.styleSheet;
}

// Get rules off the sheet object
var mainRules;
if (mainStyles.cssRules) {
  mainRules = mainStyles.cssRules;
} else if (mainStyles.rules) {
  mainRules = mainStyles.rules;
}

// Notes for Rules
// http://help.dottoro.com/ljnefpqb.php

// Iterate through the stylesheet rules
var theKey;
for (key in mainRules) {
  // Make sure key is valid
  if (typeof mainRules[key].selectorText != "undefined") {
    // The string will be the name of the selector that is to be removed
    if (
      "#paragraph-is-orange-when-hover:hover" == mainRules[key].selectorText
    ) {
      // Coercing the string key to a number key
      theKey = key * 1;
    }
  }
}

// Remove the rule
if (mainStyles.deleteRule) {
  mainStyles.deleteRule(theKey);
} else {
  mainStyles.removeRule(theKey);
}

// Notes for Deleting Rules
// deleteRule: http://help.dottoro.com/ljcihbgl.php
// removeRule: http://help.dottoro.com/ljdupbal.php

// Note: Chrome-based browser only allow stylesheet manipulation
// if the parameter "--allow-file-access-from-files" is set for local file access
// http://www.chrome-allow-file-access-from-file.com/

Offline Demo