Skip to content

Instantly share code, notes, and snippets.

@ccapndave
Created September 19, 2016 13:14
Show Gist options
  • Save ccapndave/2e465f075a7c8a5ae24d306b6ba72c97 to your computer and use it in GitHub Desktop.
Save ccapndave/2e465f075a7c8a5ae24d306b6ba72c97 to your computer and use it in GitHub Desktop.
/**
* Update a style in the stylesheet. This is very unfunctional, but unfortunately due to Javascript's ridiculous array-like
* objects this is the only efficient way to do it.
*
* @param {Document} doc
* @param {string} cssSelector
* @param {(style: CSSStyleDeclaration) => void} updater
* @returns {boolean}
*/
function updateStyleRule(doc: Document, cssSelector: string, updater: (style: CSSStyleDeclaration) => void): boolean {
const stylesheets = doc.styleSheets || document.styleSheets;
for (let n = 0; n < stylesheets.length; n++) {
const stylesheet: CSSStyleSheet = <CSSStyleSheet>stylesheets.item(n);
for (let i = 0; i < stylesheet.rules.length; i++) {
const rule = stylesheet.rules.item(i);
if (rule.type === rule.STYLE_RULE && (<CSSStyleRule>rule).selectorText === cssSelector) {
updater((<CSSStyleRule>rule).style);
return true;
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment