Skip to content
Advertisement

Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself)

Is it possible to alter a CSS stylesheet using JavaScript?

I am NOT talking about:

document.getElementById('id').style._____='.....';

I AM talking about altering:

#id {
    param: value;
}

besides doing something dirty (which we haven’t tried yet btw), like creating a new object in the head, innerHTML a style tag in there, etc. Although this, even if it did work, would pose a few issues as the style block is already defined elsewhere, and I’m not sure when/if the browser would even parse a dynamically created style block?

Advertisement

Answer

Yes you can; every browser supports this, including IE9+).

  • The insertRule() method allows dynamic addition of rules to a stylesheet.

  • With deleteRule(), you can remove existing rules from a stylesheet.

  • Rules within a stylesheet can be accessed via the cssRules attributes of a stylesheet.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement