modify a css rule object with javascript
You could use the cssRules
on the DOM stylesheet object corresponding to your original stylesheet to modify your rule.
var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;
rules[0].style.color = 'red';
Note that IE uses rules
instead of cssRules
.
Here is a demonstration: http://jsfiddle.net/8Mnsf/1/
How to dynamically modify CSS rule set (e.g. with a class selector) from JavaScript within Firefox Add-on using XUL, SDK or WebExtensions techniques?
5) There's things like document.styleSheets which doesn't seem to get what I want (unless I am mistaken?). Everything seems read-only.
This is the correct option. While the styleSheets
property is read-only (meaning you can't assign like this: document.styleSheets = val
), the stylesheet object you get does allow modifications.
Since you only care about one (modern!) browser, this is easier than Changing a CSS rule-set from Javascript in a cross-browser way. A trivial example:
function changeCSS() {
let myClassRule = document.styleSheets[0].cssRules[0];
if (myClassRule.style.color == "red")
myClassRule.style.color = "blue";
else
myClassRule.style.color = "red";
}
.my-class {
color: red;
}
<p class="my-class">First paragraph</p>
<p class="my-class">Second paragraph</p>
<button onclick="changeCSS()">Change the stylesheet!</button>
Changing a CSS rule-set from Javascript
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).
I managed to get it to work with Firefox and IE - I couldn't in Chrome, though it appears that it supports the DOM methods.ricosrealm reports that it works in Chrome, too.
Modifying of css by document.styleSheets
Modifying styleSheets directly can be tricky.
I prefer to append a new style
element to the document and place the modified CSS in there. Since it is the last style element in the document, it will override any earlier CSS rule that has a matching selector.
For example, this will set the font size of the body to 1rem:
let style = document.createElement('style');
style.innerHTML = 'body { font-size: 1rem; }';
document.head.appendChild(style);
Update CSS rule property value
If you wan to change the css rules of the ".tile" class, then you can do it.
There is a post that explains it very well :
function changeBackgroundImage(className, value){
var ss = document.styleSheets;
for (var i=0; i<ss.length; i++) {
var ss = document.styleSheets;
var rules = ss[i].cssRules || ss[i].rules;
for (var j=0; j<rules.length; j++) {
if (rules[j].selectorText === className) {
rules[j].style.backgroundImage = value;
}
}
}
}
You can call it like this :
changeBackgroundImage(".tile","url(tile.jpg)");
Update or remove css rule from insertRule() in JS
To delete just use deleteRule() passing in the index that the rule was inserted at
var index = document.styleSheets[0].insertRule(`#li${i}:after {content: "${data[2][i]}"; }`, 0);
document.styleSheets[0].deleteRule(index);
In order to update a rule access the cssRules
list at the index the rule was inserted at, and change the style property
document.styleSheets[0].cssRules[index].style.content = "";
Note you will not be able to access the rule if the style sheet being accessed was linked externally as cssRules
will be null. So you will have to delete it and insert it back to change its styles.
Demo
var stylesheet = document.styleSheets[0];
var ruleIndex = 0;
function redRule(){
stylesheet.cssRules[ruleIndex].style.color = "red";
}
function blueRule(){
stylesheet.cssRules[ruleIndex].style.color = "blue";
}
function replaceRule(){
stylesheet.deleteRule(ruleIndex);
ruleIndex = stylesheet.insertRule("body { color:yellow; }",0);
}
ruleIndex = stylesheet.insertRule("body { color:black; }",0);
document.addEventListener('click',function(e){
switch(e.target.id){
case 'red':
redRule();
break;
case 'blue':
blueRule();
break;
case 'replace':
replaceRule();
break;
}
});
<style></style>
Text<br>
<button id="red">Change rule to red</button><br>
<button id="blue">Change rule to blue</button><br>
<button id="replace">Replace rule</button><br>
Change a CSS stylesheet's selectors' properties
- Use an external stylesheet
- Identify its order on the page
- Modify the properties of the rules
Here's how to do that:
// ssMain is the stylesheet's index based on load order. See document.styleSheets. E.g. 0=reset.css, 1=main.css.
var ssMain = 1;
var cssRules = (document.all) ? 'rules': 'cssRules';
function changeCSSStyle(selector, cssProp, cssVal) {
for (i=0, len=document.styleSheets[ssMain][cssRules].length; i<len; i++) {
if (document.styleSheets[ssMain][cssRules][i].selectorText === selector) {
document.styleSheets[ssMain][cssRules][i].style[cssProp] = cssVal;
return;
}
}
}
Make sure that the rule that you want to modify already exist in the CSS file and are in the correct cascading order, even if they're empty. Otherwise, if a selector doesn't have a rule, you would have to use document.styleSheets[index].insertRule()
for which you would have to specify where in the list of rules should the rule be inserted.
changeCSSStyle('.warning', 'color', 'red');
changeCSSStyle('td.special', 'fontSize', '14px');
Related Topics
State Not Updating When Using React State Hook Within Setinterval
Static Variables in JavaScript
Converting a Js Object to an Array Using Jquery
Deleting Objects in JavaScript
Converting Between Strings and Arraybuffers
Black and White Text Based on Background Image with CSS
Override Styles in a Shadow-Root Element
Get the Size of a CSS Background Image Using JavaScript
Dynamically Expand Height of Input Type "Text" Based on Number of Characters Typed into Field
Jquery Validate Plugin - How to Create a Simple Custom Rule
How to Invoke a Jsf Managed Bean on a HTML Dom Event Using Native JavaScript
How to List the Properties of a JavaScript Object
How to Find the Operating System Details Using JavaScript