user123123123 user123123123 - 1 year ago 92
CSS Question

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;

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?

Answer Source

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].insertRule('.another-class { ' + cssText + ' }', 0);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download