Skip to content

Instantly share code, notes, and snippets.

@jphastings
Last active December 14, 2015 09:38
Show Gist options
  • Save jphastings/5065874 to your computer and use it in GitHub Desktop.
Save jphastings/5065874 to your computer and use it in GitHub Desktop.
Adds CSS to a page via JavaScript

This function will add CSS to an entire page.

addGlobalCss(".item { display:none; }",'toggle_id')

Will hide all elements with the 'item' class but, unlike $('.item').hide() it will also ensure any elements with that class that are subsequently added to the page will also be hidden.

The reference_id is used as the id of the tag added, meaning that a second call to this function with the same reference_id will remove the previous CSS.

function addGlobalCss(css,reference_id) {
if (reference_id != undefined) {
var link = document.getElementById(reference_id);
if (link) {
if (link.tagName != 'LINK' || (link.rel != 'stylesheet' && link.type != 'text/css')) {
throw("Element with id #"+reference_id+" isn't a stylesheet.");
}
link.parentNode.removeChild(link);
}
}
var link = document.createElement('link');
if (reference_id != undefined) {
link.id = reference_id;
}
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = 'data:text/css;charset=utf-8,'+encodeURIComponent(css);
document.getElementsByTagName('head')[0].appendChild(link);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment