2

I try to insert a css rule with typescript based on https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript. The method insertRule is not recognized. I have the following error:

Type 'StyleSheet' is not assignable to type 'CSSStyleSheet'. Property 'cssRules' is missing in type 'StyleSheet'.

Here is my code:

let stylesheet: CSSStyleSheet = document.styleSheets[0];
stylesheet.insertRule(".scroll-content { overflow: hidden;}",0);

I'm working with ionic 2 and angular 2.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Olivier P
  • 953
  • 1
  • 8
  • 13

3 Answers3

0

Try this snippet for defining your stylesheet slightly modified from this answer.

if (document.styleSheets[0].cssRules)
    let stylesheet: CSSStyleSheet = document.styleSheets[0].cssRules[0];
else if (document.styleSheets[0].rules)
    let stylesheet: CSSStyleSheet = document.styleSheets[0].rules[0];
Community
  • 1
  • 1
Script_Coded
  • 709
  • 8
  • 21
0

You basically need to convert that var into a CSSStyleSheet , right after retrieving the current stylesheet.

This code will work for you:

let stylesheet= document.styleSheets[0];
(stylesheet as CSSStyleSheet).insertRule(".scroll-content { overflow: hidden;}",0);
Alberto S.
  • 1,805
  • 23
  • 39
0

If someone comes here from the future, I had a similar issue with Typescript and 'CSSStyleSheet':

Property 'replaceSync' does not exist on type 'CSSStyleSheet'

Turns out the default Typescript interface was incomplete. I fixed it by adding my own like below, notice the last two rules which are missing on the default interface for some reason:

/* 
   declarations.d.ts
   Or wherever tsconfig.json is looking for .ts files in your project
*/

interface CSSStyleSheet {
  readonly cssRules: CSSRuleList
  readonly ownerRule: CSSRule | null
  readonly rules: CSSRuleList
  addRule(selector?: string, style?: string, index?: number): number
  deleteRule(index: number): void
  insertRule(rule: string, index?: number): number
  removeRule(index?: number): void
  replace(reset_style: string | CSSStyleSheet): Promise<void>
  replaceSync(reset_style: string | CSSStyleSheet): void
}