Disable Stylesheets with JavaScript

Revile those Styles

If the styles of stylesheets are atrocious and you have no control over its loading, you may want to disable specific stylesheets with javascript.

However, this may not be good idea because javascript may not be enabled in the browser such that the following will not work, but this post will show that it could be done for learning purposes.

Suppose there are three stylesheets that modify the body of the page that are located in the header. Lets say the goal is to disable the first and third stylesheet in the header.

Three Stylesheets
1
2
3
4
5
6
7
8
9
10
<head>
<!-- First stylesheet turns the body red -->
<link id="just-a-stylesheet" rel="stylesheet" href="someStyle.css" />

<!-- Second stylesheet turns the body green -->
<link rel="stylesheet" href="second.css" />

<!-- Third stylesheet turns the body yellow -->
<link rel="stylesheet" href="third.css" />
</head>

Since the first stylesheet has an id, it will be made use of. The following selects the first stylesheet and turns the JQuery object to a DOM element and disables the stylesheet.

Disable the First Stylesheet
1
$('#just-a-stylesheet')[0].disabled = true;

The third stylesheet does not have an id for referencing, so the href will be use to identify the third.

Then Disable the Third Stylesheet
1
$('head').children('link[href="third.css"]')[0].disabled = true;

The final result of this will make the body green because only the second stylesheet will remain active.

Offline Demo