Skip to content

Instantly share code, notes, and snippets.

@d4mation
Created February 16, 2022 20:23
Show Gist options
  • Save d4mation/1fb7ad7970a95c68ba31f903533700a8 to your computer and use it in GitHub Desktop.
Save d4mation/1fb7ad7970a95c68ba31f903533700a8 to your computer and use it in GitHub Desktop.
Copies CSS rules from one selector to another. Useful in cases where you want to snag some already-loaded CSS from code you don't have control over.
/**
* Copies all CSS from one selector to another
* This is done by searching for a selector and then replacing it with another
*
* @param object replacements Selector => Replacement
* @param string stylesheethref Only check Stylesheets with this in its href attribute
*
* @since {{VERSION}}
* @return void
*/
var copyRules = function( replacements, stylesheethref ) {
let stylesheets = Array.from( document.styleSheets );
if ( typeof stylesheethref !== 'undefined' && stylesheethref.length >= 0 ) {
stylesheets = stylesheets.filter( function( item ) {
if ( typeof item.href == 'undefined' || item.href == null ) return false;
return item.href.indexOf( stylesheethref ) >= 0;
} );
}
// Can only work if we can read this
stylesheets = stylesheets.filter( function( item ) {
return typeof item.cssRules !== 'undefined';
} );
let newCSS = [];
for ( let stylesheetIndex in stylesheets ) {
let stylesheet = stylesheets[ stylesheetIndex ],
rules = Array.from( stylesheet.cssRules );
for ( let ruleIndex in rules ) {
let rule = rules[ ruleIndex ],
css = rule.cssText;
for ( let selector in replacements ) {
let replacement = replacements[ selector ],
regex = new RegExp( selector, 'gi' );
css = css.replace( regex, replacement );
regex.lastIndex = 0;
}
// No change, bail
if ( css == rule.cssText ) continue;
newCSS.push( css );
}
}
if ( newCSS.length <= 0 ) return;
let head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement( 'style' );
head.appendChild( style );
style.appendChild( document.createTextNode( newCSS.join( "\n" ) ) );
}
export {
copyRules
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment