1

I have a page with a couple CSS files. I want to call a new CSS file (not present on page load) when a button is clicked. I want the other CSS files to remain unchanged though.

This works - but, it seems to replace ALL the css files and ONLY pulls styles from the new one I call. How can I keep the existing styles in place and only override what I'm targeting in this new file?

$(function () {
    $('button').click(function () {
        $('link').attr('href', 'foo.css');
    });
});
Albzi
  • 15,431
  • 6
  • 46
  • 63
user3390251
  • 317
  • 2
  • 5
  • 22
  • This question was answered many times on SO: http://stackoverflow.com/questions/5680657/adding-css-file-with-jquery – David H. Jul 29 '16 at 14:11
  • Your code doesn't work because it's not doing what you think it should do. You're REPLACING rather than adding. The duplicate solution I (and others) have provided answers your DESIRED results. – Robert Jul 29 '16 at 14:33

3 Answers3

2
  function addStyles(url){
     $('<link href="'+url+'" rel="stylesheet"/>').appendTo('head');
  }

  $(function () {
      $('button').click(function () {
          addStyles('foo.css');
      });
  });
Naveen I
  • 5,695
  • 2
  • 15
  • 8
1

Actually, you are replacing attributes of link element(s) on your page. What you should do is creating new element and appending this newly created element to the page.

/*create new element */
var newLinkElement = $('<link>').attr('href', 'foo.css');
/*append to head*/
$('head').append($(newLinkElement));
Tuğca Eker
  • 1,493
  • 13
  • 20
0

Just append to the header

$('head').append('<link rel="stylesheet" href="css/style2.css" type="text/css" />');