Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a CSS rule-set from Javascript

Tags:

javascript

css

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.

like image 518
KJ Saxena Avatar asked Sep 11 '09 06:09

KJ Saxena


People also ask

Can you modify CSS with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

How do I change CSS runtime?

You could change it any of the following ways: Adding a style declaration in the page. Adding an inline style declaration on the element. Using jQuery to change the style of the element.


2 Answers

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.

like image 99
Alex Gyoshev Avatar answered Sep 22 '22 09:09

Alex Gyoshev


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'; 

Also document.styleSheets list references of the CSSStylesSheets Objects. Other way to acces a specific sytleSheet in the page is by assigning an id to the style or link element in the html code, and get it in javascript using document.getElementById('my-style').sheet. This are some useful methods:

Major Browsers and IE9+ : insertRule(), deleteRule(), removeProperty().

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

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

It is also possible to dynamically create a new style element to store dynamic created styles, I think should be way to avoid conflicts.

like image 42
Jorge Gonzalez Avatar answered Sep 21 '22 09:09

Jorge Gonzalez