Manipulating Stylesheets with Greasemonkey

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

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);
If you enjoyed this article, please share it with a friend!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>