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 ?
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>
var link = $('link[title="mystyle"]') ? then link.remove()?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.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 :)
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');