Is there a quick and easy way to 'permanently' change properties of CSS with Javascript, D3JS, or JQuery? I've found this question which will change geometry already existing:
$('.myClass').css({ ...Your CSS properties here... });
However, I want to change a CSS property so that the geometry that is created in that session will have these updated changes as well. How can I, using Javascript, change the CSS class below from a stroke of steelblue to a stroke of light grey?
.P0{ fill:none; stroke-width:1.25px; stroke:steelblue;}
Magic CSS colour changing fiddle:
http://fiddle.jshell.net/8xkv3/3/
The key idea is to access the last stylesheet in the CSS Object Model, and add at the end of that stylesheet a CSS rule specifying the property you want for the selector you want. You want the last rule of the last stylesheet, so that it over-rides anything else in the cascade (except inline styles, of course).
The stylesheet objects in effect for the document are available as a list at
document.styleSheets
. Each one has a propertycssRules
which is a list of rules, which each represent a selector plus a list of property-value pairs.The
stylesheet.insertRule()
method creates a new rule from a string, and adds it to the sheet at the specified index. Unfortunately, it just returns the index, not the rule object, so we have to re-select it to save for future modification.You could just repeatedly add on new rules, each over-riding the previous, but that's not very efficient. The rule object has a "style" map with keys and values acting pretty much as you'd predict.
Edit
I realized there is a problem with the above approach. What happens if the last stylesheet in the list isn't being used by the current web-page? What if it's a print stylesheet? Or a stylesheet for tiny screenss, or speech synthesizers, or any other media-query limited situation? You could add a rule to that stylesheet object, but it wouldn't have any effect.
Clearly, what you need to do is create a new stylesheet object with no restrictions and/or with only the restrictions you chose. Then you can add this stylesheet to the end of the list and add your dynamic style rules to it.
You can't create a stylesheet object directly, but you can create a
<style>
element and add it to the html head object in the DOM. When the<style>
object is added to the document a stylesheet object will be created for it, and can be accessed as the.sheet
property of the element.The amended fiddle is here: http://fiddle.jshell.net/8xkv3/6/
Key code:
By the way, I don't know why this didn't show up when I searched MDN previously, but here's a good article on the various ways of dynamically manipulating the CSS OM:
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Using_dynamic_styling_information