Changing a CSS rule-set from Javascript

Asked
Active3 hr before
Viewed126 times

7 Answers

changing
90%

This function returns a CSSStyleRule that you can use like this:,Thanks for contributing an answer to Stack Overflow!,While setAttribute is nice, there is a standard way of doing this across most browsers:,You can, but it's rather cumbersome. The best reference on how to do it is the following article: Totally Pwn CSS with Javascript (web archive link).

This is a modern version based on Totally Pwn CSS with Javascript. It's ES6 I hope don't mind.

function getCSSRule(ruleName) {
   ruleName = ruleName.toLowerCase();
   var result = null;
   var find = Array.prototype.find;

   find.call(document.styleSheets, styleSheet => {
      result = find.call(styleSheet.cssRules, cssRule => {
         return cssRule instanceof CSSStyleRule &&
            cssRule.selectorText.toLowerCase() == ruleName;
      });
      return result != null;
   });
   return result;
}

This function returns a CSSStyleRule that you can use like this:

var header = getCSSRule('#header');
header.style.backgroundColor = 'red';

Major Browsers, Firefox? and IE9+ : setProperty().

< stye id = "my-style"...
   ....
var myStyle = document.getElementById('my-style').sheet
myStyle.insertRule('#header { background: red; }', 0);
load more v
88%

4 Adding and Removing Rules,5 Changing Element Styles,3 Style Sheet Properties,6 Element Class Names

You can also add new style sheets to the page — you can use the document.createElement function to create a new style element. This is useful when you want to give site visitors the option of changing your site styles dynamically, using some button controls perhaps. Here is a quick example of how you could create a new style sheet:

var sheet = document.createElement('style')
sheet.innerHTML = "div {border: 2px solid black; background-color: blue;}";
document.body.appendChild(sheet);
load more v
72%

Is it possible to make changes to a CSS rule-set dynamically (i.e. some JS which would change a CSS rule-set when the user clicks a widget),This particular CSS rule-set is applied to lots of elements (via a class selector) on the page and I want to modify it when the user clicks the widget, so that all the elements having the class change.,It is also possible to dynamically create a new style element to store dynamic created styles, I think should be way to avoid conflicts.,This function returns a CSSStyleRule that you can use like this:

This is a modern version based on Totally Pwn CSS with Javascript. It's ES6 I hope don't mind.

function getCSSRule(ruleName) {
   ruleName = ruleName.toLowerCase();
   var result = null;
   var find = Array.prototype.find;

   find.call(document.styleSheets, styleSheet => {
      result = find.call(styleSheet.cssRules, cssRule => {
         return cssRule instanceof CSSStyleRule &&
            cssRule.selectorText.toLowerCase() == ruleName;
      });
      return result != null;
   });
   return result;
}

This function returns a CSSStyleRule that you can use like this:

var header = getCSSRule('#header');
header.style.backgroundColor = 'red';

Major Browsers, Firefox? and IE9+ : setProperty().

< stye id = "my-style"...
   ....
var myStyle = document.getElementById('my-style').sheet
myStyle.insertRule('#header { background: red; }', 0);
load more v
65%

Modify a stylesheet rule with CSSOM,In this example the background of the page is set to red using CSS. The JavaScript then accesses the property using the CSSOM and changes the background to blue.,Modify an element's style,More important than the two properties noted here is the use of the style object to set individual style properties on an element:

<html>
<head>
<title>Modifying a stylesheet rule with CSSOM</title>
<style type="text/css">
body {
 background-color: red;
}
</style>
<script type="text/javascript">
var stylesheet = document.styleSheets[0];
stylesheet.cssRules[0].style.backgroundColor="blue";
</script>
</head>
<body>
The stylesheet declaration for the body's background color is modified via JavaScript.
</body>
</html>
load more v
75%

The point here is that you can control the CSS style setting on any individual element in your document with JavaScript. You fetch the element's style object, and you can then use the property name to change the setting. ,In JavaScript, each stylesheet has an array of rules that contain all of the CSS settings. However, Microsoft Internet Explorer uses a different property name for the rules array than most other browsers and you must account for that in your script, as in: ,This block of text remains hidden until the user clicks on the link. The JavaScript function I used named "toggleVis" will also hide this DIV when the user clicks on the link a second time. Try it and see. ,To demonstrate how to change a rule within a stylesheet, I also created a function called toggleColor that swaps the font color on the selected class rule.

  function toggleDisplay(id) {
     var theElement = document.getElementById(id);
     if (theElement.style.display == 'none') {
        theElement.style.display = 'block';
     } else {
        theElement.style.display = 'none';
     } // endif display
     return false;
  } // end toggleDisplay()
load more v
40%

Creating and get reference to the new stylesheet with Javascript :,Adding the keyframes rule to an element with Javascript or jQuery is not possible.,Sometimes the requirement is such that there is no option, other than using Javascript to add CSS to a stylesheet.,You must be wondering what would be the real need to add CSS rules to a stylesheet with Javascript. A better way would be to just hard-code the CSS properties in the stylesheet? Or changing the CSS properties of the element with Javascript will also work?

One such case is the CSS keyframes rule. Consider the below CSS rule :

@keyframes outlightbox {
   0 % {
      height: 100 % ;
      top: 0 px;
   }
   100 % {
      height: 500 px;
      top: 50 px;
   }
}
load more v
22%

Like we saw in the introduction, we have two ways to alter the style of an element using JavaScript. One way is by setting a CSS property directly on the element. The other way is by adding or removing class values from an element which may result in certain style rules getting applied or ignored. Let's look at both of these cases in greater detail., When it comes to styling some content, the most common way is by creating a style rule and have its selector target an element or elements. A style rule would look as follows:,Got a question or just want to chat? Comment below or drop by our forums (they are actually the same thing!) where a bunch of the friendliest people you'll ever run into will be happy to help you out!, JavaScript is very picky about what makes up a valid property name. Most names in CSS would get JavaScript's seal of approval, so you can just use them straight-up from the carton. There are a few things to keep in mind, though.

When it comes to styling some content, the most common way is by creating a style rule and have its selector target an element or elements. A style rule would look as follows:

.batman {
   width: 100 px;
   height: 100 px;
   background - color: #333;
}
load more v

Other "changing-undefined" queries related to "Changing a CSS rule-set from Javascript"