Is it possible to set the cssText property of a cssRule
Asked Answered
M

4

6

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/

Mcintosh answered 5/9, 2013 at 17:59 Comment(0)
S
7

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.

Senator answered 5/9, 2013 at 18:5 Comment(0)
D
0

Actually your code is working as aspected.

CSSRule.cssText: cssText returns the actual text of the style rule

Check this Using dynamic styling information

Delisle answered 5/9, 2013 at 18:7 Comment(0)
S
0

Javascript DOM style

  var div = document.querySelectorAll("div");
 
  div[0].style.cssText = "border: 5px solid yellow; padding: 10px"; 
  div[1].setAttribute("style", "border: 5px solid red; margin: 20px");
<div>cssText yellow</div>
<div>setAttribute red</div>
Saunder answered 22/12, 2017 at 4:6 Comment(0)
K
0

VanillaJS:

selector is any CSS selector you want.

in style you can write any valid CSS Property : Value.

for(CSSStyleRule of cssText.cssRules ){
    if(CSSStyleRule.selectorText === selector){

      CSSStyleRule.style = 'color : yellow';
Kerenkeresan answered 2/10, 2024 at 6:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.