3

I created a button that ADD CSS file to the page header. How Can I REMOVE this CSS from the header with the second click on the same button?

Thanks

<script>
$(document).ready(function(){
  $("#myButton").click(function(){
  var ls = document.createElement('link');
  ls.rel="stylesheet";
  ls.href="myCSSfile.css";
  document.getElementsByTagName('head')[0].appendChild(ls);
    });

});
</script>


<button id="myButton">Add / Remove</button>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Ed Nez
  • 53
  • 5
  • Possible repeat - http://stackoverflow.com/questions/3182840/removing-or-replacing-a-stylesheet-a-link-with-javascript-jquery – Nirvik Baruah Aug 07 '16 at 15:58

2 Answers2

5

Just add something to identify the style tag, an ID seems appropriate

$(document).ready(function(){
    $("#myButton").on('click', function(){

        if ( $('#myStyle').length === 0 ) { // does not yet exist

            $('<link />', {
                id   : 'myStyle',
                rel  : 'stylesheet',
                href : 'myCSSfile.css'
            }).appendTo('head');

        } else { // exists, remove it

            $('#myStyle').remove();

        }
    });
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thanks! Works! My final code: – Ed Nez Aug 07 '16 at 16:14
  • 1
    I think this `href : 'myCSSfile.css';` line should not contain a terminator `;` – Tariqul Islam Aug 08 '20 at 22:27
1

In addition to the answer above you could also do this. This code helps you to identify the link tag on the basis of the css file you included, no need to specially identify the link tag using the id attribute :

<script>
$(document).ready(function(){
  $("#myButton").click(function(){


        if($("link[href*=myCSSfile]").length){
            $("link[href*=myCSSfile]").remove();
        }
        else{
            var ls = document.createElement('link');
            ls.rel="stylesheet";
            ls.href="myCSSfile.css";
            document.getElementsByTagName('head')[0].appendChild(ls);
        }
    });

});
</script>


<button id="myButton">Add / Remove</button>
Kiran Yallabandi
  • 2,544
  • 2
  • 22
  • 25