Removing or replacing a stylesheet (a <link>) with JavaScript/jQuery

To cater for ie you have to set the stylesheet to be disabled as it keeps the css styles in memory so removing the element will not work, it can also cause it to crash in some instances if I remember correctly.

This also works for cross browser.

e.g

document.styleSheets[0].disabled = true;

//so in your case using jquery try

$('link[title=mystyle]')[0].disabled=true;

I managed to do it with:

$('link[title="mystyle"]').attr('disabled', 'disabled');

it seems this is the only way to remove the styles from memory. then I added:

$('link[title="mystyle"]').remove();

to remove the element too.


To disable your selected stylesheet:

$('link[title="mystyle"]').prop('disabled', true);

If you never want that stylesheet to be applied again, you can then .remove() it. But don’t do that if you want to be able to re-enable it later.

To re-enable the stylesheet, do this (as long as you didn’t remove the stylesheet’s element):

$('link[title="mystyle"]').prop('disabled', false);

In the code above, it is important to use .prop, not .attr. If you use .attr, the code will work in some browsers, but not Firefox. This is because, according to MDN, disabled is a property of the HTMLLinkElement DOM object, but not an attribute of the link HTML element. Using disabled as an HTML attribute is nonstandard.


no jQuery solution

if you can add id to your link tag

<link rel="stylesheet" href="css/animations.css" id="styles-animations">

document.getElementById("styles-animations").disabled = true;

if you know index position of your css file in document

document.styleSheets[0].disabled = true; // first
document.styleSheets[document.styleSheets.length - 1].disabled = true; // last

if you want to disable style by name you can use this function

/**
 * @param [string]  [styleName] [filename with suffix e.g. "style.css"]
 * @param [boolean] [disabled]  [true disables style]
 */
var disableStyle = function(styleName, disabled) {
    var styles = document.styleSheets;
    var href = "";
    for (var i = 0; i < styles.length; i++) {
        href = styles[i].href.split("/");
        href = href[href.length - 1];

        if (href === styleName) {
            styles[i].disabled = disabled;
            break;
        }
    }
};

note: make sure style file name is unique so you don't have "dir1/style.css" and "dir2/style.css". In that case it would disable only first style.


Using pure javascript:

var stylesheet = document.getElementById('stylesheetID');
stylesheet.parentNode.removeChild(stylesheet);