55

Am wondering how it would be possible to unload a CSS from a page. e.g. In my page I have included a file called a.css. Now I want the user to be able to change the theme, which is CSS driven, thus he/she should be able to unload a.css and then I can load b.css (else they will conflict)

Any idea how to go about this?

Alec Smart
  • 94,115
  • 39
  • 120
  • 184
  • I do not know how, but the ExtJS framework offers such kind of functions, so if the solutions here do not work, you could have a look there.... – TheHippo Oct 21 '09 at 10:14

4 Answers4

73

Take the link element and disable it

document.getElementsByTagName('link')[0].disabled = true; 
Xinus
  • 29,617
  • 32
  • 119
  • 165
  • This is wrong because the link tag is not used only for CSS. See this page https://www.w3schools.com/tags/tag_link.asp – Cpp Forever Apr 02 '19 at 13:01
  • 4
    @CppForever Yes. But at the same time the answer is still valid and helpful since it leads us in the right direction. If needed, we can check the values of `href`, `rel`, etc. Such operations, however, are just implementation details. At least, the answer is not "wrong" as you say, I believe. – ynn May 17 '20 at 06:59
  • 2
    One important warning is that `link` doesn't support `disabled` attribute (see [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/disabled)). Actually it may work but that's not standard-compliant. – ynn May 18 '20 at 10:09
32

With jquery, this works:

$("link[href='fileToRemove.css']").remove();

Obviously, replace fileToRemove.css with the relative path and filename of the file to be unloaded.

Rene Pot
  • 24,681
  • 7
  • 68
  • 92
Gullbyrd
  • 1,545
  • 1
  • 16
  • 14
9
var firstLink = document.getElementsByTagName('link')[0];
firstLink.parentNode.removeChild(firstLink)

This would remove the first link element on the page - not sure how your html is structured but I'm sure you can use it as an example. You might want to check the type attribute if it's 'text/css' and you're targeting the right media (screen), or possibly check if the href contains 'css' anywhere if you have other link elements that aren't css references.

Note you can also re-set the href attribute to point to a non-existing page instead of removing the element entirely.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
3

Oddly enough, IE and firefox support the disabled attribute, but neither Chrome, Safari, nor Opera support it. So, this should be the most cross-browser solution.

// Disables a particular stylesheet given its DOM Element
function unload_stylesheet(DOMelement){
    DOMelement.disabled = true;
    DOMelement.parentNode.removeChild( DOMelement );
    DOMelement.href = "data:text/css,"; // empty stylesheet to be sure
}

// Usage:
unload_stylesheet( document.getElementsByTagName('link')[0] );
Jack G
  • 4,553
  • 2
  • 41
  • 50