Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Can i dynamically create a CSSStyleSheet object and insert it?

Tags:

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?

like image 662
ayanamist Avatar asked Nov 21 '11 08:11

ayanamist


People also ask

How to change stylesheet dynamically using 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.

How to add style attribute dynamically in JavaScript?

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.

Can you dynamically change CSS?

It is worth noting that while pre/postprocessor variables are only used at compilation-time, CSS variables can be used and updated dynamically.

Can JavaScript affect CSS?

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.


1 Answers

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

like image 107
WickyNilliams Avatar answered Sep 21 '22 21:09

WickyNilliams