Disable Stylesheets with JavaScript

11/04/2013, Mon
Categories: #JavaScript
Tags: #jQuery

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. Let's say the goal is to disable the first and third stylesheet in the header.

<!-- Three Stylesheets -->

<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, this will be used. The following selects the first stylesheet and turns the JQuery object to a DOM element and disables the stylesheet.

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

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

// Then Disable the Third Stylesheet
$("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