Ginpei
Ginpei

Reputation: 3178

Remove CSS rules by JavaScript

How to remove CSS rules by JavaScript?

var elStyle = document.querySelector('style#the-style');
var stylesheet = elStyle.sheet;
var rules = stylesheet.cssRules;
for (var i=0; i<rules.length; i++) {
  var rule = rules[i];
  if (rule.selectorText === '#rule2 em') {
    // TODO: remove this rule
    break;
  }
}

http://jsfiddle.net/e3zebmqv/

I succeeded to remove the style by rule.style.color='' but the rule still exists. Are there any APIs to remove? Or should I use innerHTML?

UPDATE

In this case, I'd like to remove style rules, not style properties.

(I don't know about Stack Overflow's rule well. I hope this editing was right.)

Upvotes: 16

Views: 18289

Answers (2)

vasilenicusor
vasilenicusor

Reputation: 2073

here is an example how you can do this:

var styleTag = document.getElementById ("the-style");
var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet;

if (sheet.cssRules) { // all browsers, except IE before version 9
    for (var i=0; i<sheet.cssRules.length; i++) {
        if (sheet.cssRules[i].selectorText === '#rule2 em') {        
            //console.log(sheet.cssRules[i]);
            sheet.deleteRule (i);
        }
    }  
}
else 
{  // Internet Explorer before version 9
    for (var i=0; i<sheet.rules.length; i++) {
        if (sheet.rules[i].selectorText === '#rule2 em') {        
            // console.log(sheet.cssRules[i]);
            sheet.removeRule (i);
        }
    } 
}

And on JSFiddle http://jsfiddle.net/n53u7cvm/1/

Upvotes: 13

Fenton
Fenton

Reputation: 250822

While it is possible to edit the stylesheet programatically, it comes with a host of browser problems.

Here is how you obtain the rules from a stylesheet:

var rules = new Array();
if (document.styleSheets[1].cssRules) {
    rules = document.styleSheets[1].cssRules;
}
else if (document.styleSheets[1].rules) {
    rules = document.styleSheets[1].rules;
}

And if you think that's a bit nasty, it gets worse from there!

Update

I can see the question has been edited...

The following works (updated JSFiddle)...

if (selector === '#rule2 em') {
    rule.style.color = 'black';
}

Upvotes: 3

Related Questions