Removing Stylesheet Rules

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!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
1
2
3
#paragraph-is-orange-when-hover:hover {
color: orange;
}
RemovingStyleSheetRules.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//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