Adding / removing css files using JQUERY

Good afternoon!

I want to add and remove CSS files according to the size of the list. My code is as follows:

$("#size_storedList").ready(function(){ var list_size = $("#size_storedList").attr('value'); if(list_size <= 4){ if ($("link").is('.size5')){ $('link.size5').removeClass(); } if ($("link").is('.size6')){ $('link.size6').removeClass(); } $('head').append('<link class="size4" rel="stylesheet" href="css/stored_list/list_size4.css" type="text/css" />'); } else if(list_size == 5){ if ($("link").is('.size4')){ $('link.size4').removeClass(); } if ($("link").is('.size6')){ $('link.size6').removeClass(); } $('head').append('<link class="size5" rel="stylesheet" href="css/stored_list/list_size5.css" type="text/css" />'); } else if(list_size == 6){ if ($("link").is('.size4')){ $('link.size4').removeClass(); } if ($("link").is('.siz5')){ $('link.size5').removeClass(); } $('head').append('<link class="size6" rel="stylesheet" href="css/stored_list/list_size6.css" type="text/css" />'); } }); 

But it's pretty dirty. What can I do to minimize the check if the file already exists or not so that I can delete it.

 if ($("link").is('.size5')){ $('link.size5').removeClass(); } 

Thanks.

+4
source share
2 answers
 <link rel="stylesheet" href="default.css" type="text/css"> <ul> <li><a id="css-red" href="#red">Red</a></li> <li><a id="css-blue" href="#blue">Blue</a></li> <li><a id="css-green" href="#green">Green</a></li> </ul> $(document).ready(function() { // red $("#css-red").click(function() { $("link[rel=stylesheet]").attr({href : "red.css"}); }); }); 

The above concept is different from you, but I think it will be a good idea. You can configure it to your current code.

+8
source

You can use the data-* attributes in the body tag and save, say data-loaded-css , the url of the current active css file.

also see $. data ()

+1
source

Source: https://habr.com/ru/post/1391208/


All Articles