Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically remove a stylesheet from the current page

Is there a way to dynamically remove the current stylesheet from the page?

For example, if a page contains:

<link rel="stylesheet" type="text/css" href="http://..." /> 

...is there a way to later disable it with JavaScript? Extra points for using jQuery.

like image 782
Nathan Osman Avatar asked Feb 17 '11 19:02

Nathan Osman


2 Answers

Well, assuming you can target it with jQuery it should be just as simple as calling remove() on the element:

$('link[rel=stylesheet]').remove(); 

That will remove all external stylesheets on the page. If you know part of the url then you can remove just the one you're looking for:

$('link[rel=stylesheet][href~="foo.com"]').remove(); 

And in Javascript

this is an example of remove all with query selector and foreach array

Array.prototype.forEach.call(document.querySelectorAll('link[rel=stylesheet]'), function(element){       try{         element.parentNode.removeChild(element);       }catch(err){}     });  //or this is similar var elements = document.querySelectorAll('link[rel=stylesheet]'); for(var i=0;i<elements.length;i++){     elements[i].parentNode.removeChild(elements[i]); } 
like image 98
Brian Donovan Avatar answered Sep 19 '22 09:09

Brian Donovan


If you know the ID of the stylesheet, use the following. Any other method of getting the stylesheet works as well, of course. This is straight DOM and doesn't require using any libraries.

var sheet = document.getElementById(styleSheetId); sheet.disabled = true; sheet.parentNode.removeChild(sheet); 
like image 32
Sir Robert Avatar answered Sep 18 '22 09:09

Sir Robert