Manipulating Stylesheets with Greasemonkey

These are pretty useful snippets for working with stylesheets in Greasemonkey, but they can be used elsewhere, as well.

Remove All Stylesheets From a Webpage

This snippet can be used to remove all stylesheets that are <link>ed to the webpage. This will not work for <style>s and inline styles:

for( i = 0; (l = document.getElementsByTagName("link")[i]); i++ ) {
    if( l.getAttribute("rel").indexOf("style") >= 0 ) l.disabled = true;
}

Linking to an External Stylesheet

This lets you append a stylesheet to the page, effectively letting you override all of the other stylesheets on the page:

var link = window.document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://example.com/styles/stylesheet.css';
document.getElementsByTagName("HEAD")[0].appendChild(link);

Overriding Styles Without a Stylesheet

This is the same concept as above, except you can use the data: protocol to specify your styles in the href attribute:

var link = window.document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'data:text/css,' +
            // Selectors start here
            '#sidebar { background: #DDD; border: solid 1px #CCC; }' +
            'P { line-height: 1.5; }';
document.getElementsByTagName("HEAD")[0].appendChild(link);
Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.