3

I am adding a specific css file dynamically when I render a segment of html using the following.

loadCss("css/customCss.css");


function loadCss(href) {
  var cssLink = $("<link rel='stylesheet' type='text/css' href='" + href + "'>");
  $("head").append(cssLink);
}

How can I remove a css file where the file path reference is say css/customCssLearning.

epascarello
  • 204,599
  • 20
  • 195
  • 236
Arianule
  • 8,811
  • 45
  • 116
  • 174
  • 2
    http://stackoverflow.com/questions/3182840/removing-or-replacing-a-stylesheet-a-link-with-javascript-jquery – epascarello Feb 04 '15 at 13:34
  • What is the point of this? It doesn't take away the styles once the page is loaded.... – Ruddy Feb 04 '15 at 13:36
  • Please update the tags on your post... it seems like you are using jQuery for your JS framework (based on your querying). – El Guapo Feb 04 '15 at 13:44

1 Answers1

3

You need to disable it, removing the element does nothing. To select the element by the href value, you need to use a attribute selector.

$('link[href="css/customCss.css"]')[0].disabled=true;

and if you are going to be adding and "removing" it, you might want to check for it first and reenable it.

function loadCss(href) {    
    var sSheet = $('link[href="' + href + '"]');      
    if (sSheet .length) {
        sSheet[0].disabled = false;
    } else {
        var cssLink = $("<link rel='stylesheet' type='text/css' href='" + href + "'>");
        $("head").append(cssLink);
    }
}

Running Example:

function loadCSS(href) {
  var sSheet = $('link[href="' + href + '"]');
  if (sSheet.length) {
    sSheet[0].disabled = false;
  } else {
    var cssLink = $("<link rel='stylesheet' type='text/css' href='" + href + "'>");
    $("head").append(cssLink);
  }
}

function removeCSS(href) {
  $('link[href="' + href + '"]')[0].disabled = true;
}



$("button.add").on("click", function() {
  loadCSS("http://cdn.sstatic.net/stackoverflow/all.css");
});

$("button.remove").on("click", function() {
  removeCSS("http://cdn.sstatic.net/stackoverflow/all.css");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h1>Hello</h1>
<div class="topbar">
  <div class="icon-achievements">
    <button class="add unread-count">Add</button>
    <button class="remove unread-count">Remove</button>
  </div>
</div>
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 1
    Is setting "disabled" to true on a `style` dom element supposed to un-apply the styles? because it doesn't seem to (Chrome). – CodingWithSpike Feb 04 '15 at 13:50
  • Works fine for me in chrome @CodingWithSpike Try the sample above I just added. – epascarello Feb 04 '15 at 13:59
  • Ah yes, my mistake. I had tried it on a ` – CodingWithSpike Feb 04 '15 at 16:23
  • That really solved it for me. Thank you. Also learned from your code. – Arianule Feb 05 '15 at 14:43