Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing or replacing a stylesheet (a <link>) with JavaScript/jQuery

How can I do this?

I tried

$('link[title="mystyle"]').remove();

and although the element is removed, the styles are still applied to the current page (in both Opera and Firefox).

Is there any other way?

like image 749
Alex Avatar asked Jul 06 '10 00:07

Alex


People also ask

How to remove CSS stylesheet in jQuery?

Approach: We will create a script that will find the global stylesheet with the id of “one” and will remove it from the head section. The find() and remove() methods of jQuery are used for this purpose.

How do I remove a CSS stylesheet?

On the left, click Website > Pages. Scroll down to the CSS & Stylesheets section, and click the X next to the stylesheet you'd like to remove.

Can you change CSS file with JavaScript?

JavaScript can change Css styles such as color, font size etc. of elements using some methods such as getElementById(), getElementByClassName() etc. In the following example font style and font size of the elements have changed using getElementById() method.


3 Answers

To cater for ie you have to set the stylesheet to be disabled as it keeps the css styles in memory so removing the element will not work, it can also cause it to crash in some instances if I remember correctly.

This also works for cross browser.

e.g

document.styleSheets[0].disabled = true; 

//so in your case using jquery try

$('link[title=mystyle]')[0].disabled=true; 
like image 147
redsquare Avatar answered Sep 20 '22 23:09

redsquare


I managed to do it with:

$('link[title="mystyle"]').attr('disabled', 'disabled');

it seems this is the only way to remove the styles from memory. then I added:

$('link[title="mystyle"]').remove();

to remove the element too.

like image 35
Alex Avatar answered Sep 19 '22 23:09

Alex


To disable your selected stylesheet:

$('link[title="mystyle"]').prop('disabled', true);

If you never want that stylesheet to be applied again, you can then .remove() it. But don’t do that if you want to be able to re-enable it later.

To re-enable the stylesheet, do this (as long as you didn’t remove the stylesheet’s element):

$('link[title="mystyle"]').prop('disabled', false);

In the code above, it is important to use .prop, not .attr. If you use .attr, the code will work in some browsers, but not Firefox. This is because, according to MDN, disabled is a property of the HTMLLinkElement DOM object, but not an attribute of the link HTML element. Using disabled as an HTML attribute is nonstandard.

like image 39
Rory O'Kane Avatar answered Sep 18 '22 23:09

Rory O'Kane