A couple of options:
If you can remove the entire stylesheet (by removing the style
or link
element), that will remove all rules defined by that stylesheet.
Live Example:
$("input").on("click", function() {
$("style").remove(); // Your selector would be more specific, presumably
});
.red {
color: red;
}
.green {
color: green;
}
.blue {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<input type="button" value="Click to remove the stylesheet">
Alternately, if you need to just remove one rule, you can, but it's a pain: You look through the styleSheets
collection to find the stylesheet object for it, then find the relevant rule in the style sheet's cssRules
list (called just rules
on older IE), probably by looking at each CSSStyleRule
's selectorText
property, then call deleteRule
to delete it.
// Loop through the stylesheets...
$.each(document.styleSheets, function(_, sheet) {
// Loop through the rules...
var keepGoing = true;
$.each(sheet.cssRules || sheet.rules, function(index, rule) {
// Is this the rule we want to delete?
if (rule.selectorText === ".containerTitle") {
// Yes, do it and stop looping
sheet.deleteRule(index);
return keepGoing = false;
}
});
return keepGoing;
});
Live Example (see comments):
$("input").on("click", function() {
// Loop through the stylesheets...
$.each(document.styleSheets, function(_, sheet) {
// Loop through the rules...
var keepGoing = true;
$.each(sheet.cssRules || sheet.rules, function(index, rule) {
// Is this the rule we want to delete?
if (rule.selectorText === ".green") {
// Yes, do it and stop looping
sheet.deleteRule(index);
return keepGoing = false;
}
});
return keepGoing;
});
});
.red {
color: red;
}
.green {
color: green;
}
.blue {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<input type="button" value="Click to remove the green rule">