Consider correctly using the DOM API to achieve what you want, rather than a complex regular expression that may not work very well:
function deleteRule(selector) {
// Get the collection of stylesheets and iterate over them
var ss = document.styleSheets;
// Exit if no stylesheets
if (!ss.length)
return;
// Create an uppercase tagname version of our selector for IE
var uSelector = selector.replace(/^[a-z]+|\s+[a-z]+/gi, function ($0) {
return $0.toUpperCase();
});
// Create a map so we don't get SO's code block scrollbars involved
var map = {};
map[selector] = map[uSelector] = 1;
// `deleteRule` for standards, `removeRule` for IE
var del = "deleteRule" in ss[0] ? "deleteRule" : "removeRule";
for (var a = 0, maxA = ss.length; a < maxA; a++) {
// `cssRules` for standards, `rules` for IE
var rules = ss[a].cssRules || ss[a].rules;
for (var b = 0, maxB = rules.length; b < maxB; b++) {
// Check for selector existence in our map
if (rules[b].selectorText in map)
ss[a][del](b); // remove using our stored delete method
}
}
}
Bear in mind that browsers may reformat the stylesheet rule's selector to include whitespace (so body>div.selector
becomes body > div.selector
). You should try and be as consistent as possible with your whitespace in your CSS selectors. If you want to delete the rule from a specific stylesheet and not all stylesheets, eliminate the first for
loop and specify the stylesheet object instead.
Example