Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox and IE can't modify cssRules

I need to change existent global CSS rules then I access document.styleSheets, obtain my rule and modify it.

I modify the selector by accessing the selectorText property.

CSS code

<style type="text/css">
    .class {
        color: #230020;
    }
</style>

JavaScript code

var rule = document.styleSheets[0].cssRules[0]; // obtain the first rule.

/* Chrome, Opera, Safari */
rule.selectorText; // returns ".class"
rule.selectorText = ".another-class";
rule.selectorText; // returns ".another-class", then it works and the rule changed.

My problem is that in all versions of Firefox and Internet Explorer, the property selectorText seems to be read-only.

/* Internet Explorer, Edge, and Firefox */
rule.selectorText; // returns ".class"
rule.selectorText = ".another-class";
rule.selectorText; // returns ".class", It remains as it was.

How can I make it work on Mozilla Firefox, Microsoft Internet Explorer and Edge?

like image 300
user123123123 Avatar asked Jul 22 '16 16:07

user123123123


1 Answers

According to the MDN, selectorText is meant to be read-only:

The CSSRule.selectorText property gets the textual representation of the selector for the rule set. This is implemented in a readonly manner; to set stylesheet rules dynamically, see Using dynamic styling information.

Unfortunately, there doesn't seem to be a cross-browser way to change the selector of a CSS rule. If that is your goal, you can try deleting the entire rule and replacing it with a new one by using the same rule index, you'll just have to include all of the rule properties along with the selector, like this:

var cssText = document.styleSheets[1].cssRules[0].style.cssText;
document.styleSheets[0].deleteRule(0);
document.styleSheets[0].insertRule('.another-class { ' + cssText + ' }', 0);

Works for me in Firefox and other browsers. See insertRule() and deleteRule().

like image 178
skyline3000 Avatar answered Sep 22 '22 16:09

skyline3000