Unload CSS from webpage

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Take the link element and disable it

document.getElementsByTagName('link')[0].disabled = true; 

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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] );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlec SmartView Question on Stackoverflow
Solution 1 - JavascriptXinusView Answer on Stackoverflow
Solution 2 - JavascriptGullbyrdView Answer on Stackoverflow
Solution 3 - Javascriptmeder omuralievView Answer on Stackoverflow
Solution 4 - JavascriptJack GView Answer on Stackoverflow