I know document.styleSheets
which consists of all valid style sheets in a page. I want to know whether i can create a new one and append it to present list via javascript.
I have tried document.styleSheets[0].constructor
, document.styleSheets[0].__proto__.constructor
, new CSSStyleSheet
, CSSStyleSheet()
, all what i get from Chrome is TypeError: Illegal constructor
. CSSStyleSheet.constructor()
returned a pure object but i expect a CSSStyleSheet object.
I know i can create a link/style element and append it, then modify it. What i want to know is that, can i create such object directly with javascript?
If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.
style. color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element.
It is worth noting that while pre/postprocessor variables are only used at compilation-time, CSS variables can be used and updated dynamically.
Ignoring inline styles, the other approach that we can use to introduce elements to the goodness that is CSS styling involves JavaScript. We can use JavaScript to directly set a style on an element, and we can also use JavaScript to add or remove class values on elements which will alter which style rules get applied.
I know you said you didn't want to create an element, but that's genuinely the only way to do it. A few people have detailed this approach above, but i notice nobody covered off that HTMLStyleElement
and HTMLLinkElement
both have a neat sheet
property to get direct access to their CSSStyleSheet
:
var style = document.createElement("style"); document.head.appendChild(style); // must append before you can access sheet property var sheet = style.sheet; console.log(sheet instanceof CSSStyleSheet);
Much simpler than searching through document.styleSheets
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With