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>
1

2 Answers 2

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();

        }
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Works! My final code: <script> $(document).ready(function(){ $("#myButton").click(function(){ if ( $('#myStyle').length === 0 ) { var ls = document.createElement('link'); ls.rel="stylesheet"; ls.id="myStyle"; ls.href="myCSSfile.css"; document.getElementsByTagName('head')[0].appendChild(ls); } else { $('#myStyle').remove(); } }); }); </script>
I think this href : 'myCSSfile.css'; line should not contain a terminator ;
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.