0

I am removing a css file and adding the file on click

To remove the file I am using

$('link[title="mystyle"]').remove();

Is there any way to add that file back to DOM once its removed ?

5 Answers 5

3

Yes, just keep a reference to it, and append/appendTo it when you want to put it back.

Removing:

var link = $('link[title="mystyle"]').remove();

Later, when you want to put it back:

link.appendTo('head');

Here's an example doing that with the style element in a Stack Snippet, but it works the same for link:

var style = null;
setInterval(function() {
  if (style) {
    style.appendTo('head');
    style = null;
  } else {
    style = $("style").remove();
  }
}, 800);
p {
  color: green;
}
<p>Testing 1 2 3</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

2 Comments

shouldn't it be var link = $('link[title="mystyle"]') ? then link.remove()?
@Riad: remove, like most jQuery methods, returns a reference to the object, so we don't have to do it separately. We can, but we don't have to.
1

How about not removing it, instead only remove the source href?

// remove
$('link[title="mystyle"]').data("href", $('link[title="mystyle"]').attr("href")).attr("href", "");

// bring back
$('link[title="mystyle"]').attr("href", $('link[title="mystyle"]').data("href"));

Comments

0

Try this

var link = '<link rel="stylesheet" type="text/css" href="' + YourFileName + '">'
$('head').append(link)

Comments

0

HTML:

<link id="custom" rel="stylesheet" type="text/css" href="style.css">
<a href="#" id="changeCss">Change CSS</a>

Jquery:

$('#changeCss').click(function(){
  if($('#custom').attr('href') != ''){
    $('#custom').attr('href', '');
  }else {$('#custom').attr('href', 'style.css')}
  return false;
})

Hope useful for you :)

Comments

0

As long as you know the stylesheet’s URL, there’s various alternatives:

var url = '//cdn.sstatic.net/Sites/stackoverflow/all.css';

/* Insert as HTML string: */
document.head.insertAdjacentHTML(
    'beforeend',
    '<link rel="stylesheet" type="text/css" href="' + url + '">'
);

/* Or, after removal, create a link element and append it: */
var styleLink = document.createElement('link');
styleLink.rel = 'stylesheet';
styleLink.type = 'text/css';
styleLink.href = url;
document.head.appendChild(styleLink);

/* Or, remove it with jQuery and save its reference: */
var linkElement = $('link[title="mystyle"]').remove();
linkElement.appendTo('head');

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.