Skip to content

Instantly share code, notes, and snippets.

@hinell
Last active December 23, 2016 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hinell/cb2c34e3754e43bcab8e17f09dd83126 to your computer and use it in GitHub Desktop.
Save hinell/cb2c34e3754e43bcab8e17f09dd83126 to your computer and use it in GitHub Desktop.
Painless CSSStyleSheet instances' rules manipulator
// Author: hinell@github.com
// Distributed under the MIT License
// Extension for CSSStyleSheet ($('style').sheet) class that enables painless manipulation of
// your css style sheets.
// Be careful! This module extendes built-in prototype!
// cssStyleSheet.rule(a?:number | string, i?: number): CSSRule | undefined
// x:number - the "x" index of cssStyleSheet.cssRules at which the CSSRule to be deleted
// x:string - new "x" CSSRule to add at last of the .cssRules index
// x:string, i:number - new "x" CSSRule to add into the .cssRules at "i" index
// no arguments - remove last CSSRule from the .cssRules
CSSStyleSheet &&
CSSStyleSheet.prototype.rule || (
CSSStyleSheet.prototype.rule = function (first,second){
var err = function(msg){ throw msg}
,firstArgStr = typeof first === 'string'
,firstArgNum = typeof first === 'number'
,seconArgNum = typeof second === 'number'
,cssrule;
switch (arguments.length) {
case 0:
cssrule = this.cssRules[this.cssRules.length - 1];
this.cssRules.length && this.deleteRule(this.cssRules.length - 1);
return cssrule;
break;
case 1:
return firstArgStr
? (this.insertRule(first, this.cssRules.length ),this.cssRules[this.cssRules.length-1])
: (firstArgNum
? (cssrule = this.cssRules[first]
,this.cssRules.length && this.deleteRule(first), cssrule)
: err('Invalid argument: string or number is expected!')
);
break;
default:
return firstArgStr && seconArgNum
? (this.insertRule(first,second),this.cssRules[this.cssRules.length-1])
: err('Invalid arguments: (string,number) is expected!');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment