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');
    });
});
2
  • This question was answered many times on SO: stackoverflow.com/questions/5680657/adding-css-file-with-jquery Commented Jul 29, 2016 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. Commented Jul 29, 2016 at 14:33

3 Answers 3

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

  $(function () {
      $('button').click(function () {
          addStyles('foo.css');
      });
  });
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Just append to the header

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.