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.)
Method 1: Using CSS removeProperty: The CSSStyleDeclaration. removeProperty() method is used to remove a property from a style of an element. The style of the element is selected by going through the styleSheets array and selecting the cssRule.
Use the removeAttribute() method to remove all styles from an element, e.g. box. removeAttribute('style') . The removeAttribute method will remove the style attribute from the element.
CSSStyleRule represents a single CSS style rule. It implements the CSSRule interface with a type value of 1 (CSSRule. STYLE_RULE).
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/
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!
I can see the question has been edited...
The following works (updated JSFiddle)...
if (selector === '#rule2 em') {
rule.style.color = 'black';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With