Search code examples
javascriptcss

Is it possible to set the cssText property of a cssRule


I'm trying to edit the cssText property of a cssRule. I've seen it done often:

Usually its done using : cssText.replace( ... ).

It seems to work for everybody except me. Can someone please explain me why the following will not work :

    var cssText = document.styleSheets[1].cssRules[0].cssText;
    document.styleSheets[1].cssRules[0].cssText = cssText.replace( "red", "yellow" );

Fiddle is here: http://jsfiddle.net/KbkFH/3/


Solution

  • You almost had it. You were just missing the style

    $( document ).ready(
    function() {
        //.style was missing
        var cssText = document.styleSheets[1].cssRules[0].style.cssText;
        document.styleSheets[1].cssRules[0].style.cssText = cssText.replace( "red", "yellow" );
        }
    );
    

    Updated fiddle: http://jsfiddle.net/KbkFH/6/

    NOTE: if the rule included a class name of redesign it would replace the class name to be yellowesign which might not be what you want. Just be careful when using replace without parsing the styles or targetting a specific style.