Removing or Replacing a Stylesheet (A ≪Link≫) With JavaScript/Jquery

Removing or replacing a stylesheet (a <link>) with JavaScript/jQuery

To cater for ie you have to set the stylesheet to be disabled as it keeps the css styles in memory so removing the element will not work, it can also cause it to crash in some instances if I remember correctly.

This also works for cross browser.

e.g

document.styleSheets[0].disabled = true;

//so in your case using jquery try

$('link[title=mystyle]')[0].disabled=true;

How to dynamically remove a stylesheet from the current page

Well, assuming you can target it with jQuery it should be just as simple as calling remove() on the element:

$('link[rel=stylesheet]').remove();

That will remove all external stylesheets on the page. If you know part of the url then you can remove just the one you're looking for:

$('link[rel=stylesheet][href~="foo.com"]').remove();

And in Javascript

this is an example of remove all with query selector and foreach array

Array.prototype.forEach.call(document.querySelectorAll('link[rel=stylesheet]'), function(element){
try{
element.parentNode.removeChild(element);
}catch(err){}
});

//or this is similar
var elements = document.querySelectorAll('link[rel=stylesheet]');
for(var i=0;i<elements.length;i++){
elements[i].parentNode.removeChild(elements[i]);
}

adding and removing a stylesheet dynamcally

You need to disable it, removing the element does nothing. To select the element by the href value, you need to use a attribute selector.

$('link[href="css/customCss.css"]')[0].disabled=true;

and if you are going to be adding and "removing" it, you might want to check for it first and reenable it.

function loadCss(href) {    
var sSheet = $('link[href="' + href + '"]');
if (sSheet .length) {
sSheet[0].disabled = false;
} else {
var cssLink = $("<link rel='stylesheet' type='text/css' href='" + href + "'>");
$("head").append(cssLink);
}
}

Running Example:

function loadCSS(href) {  var sSheet = $('link[href="' + href + '"]');  if (sSheet.length) {    sSheet[0].disabled = false;  } else {    var cssLink = $("<link rel='stylesheet' type='text/css' href='" + href + "'>");    $("head").append(cssLink);  }}
function removeCSS(href) { $('link[href="' + href + '"]')[0].disabled = true;}


$("button.add").on("click", function() { loadCSS("http://cdn.sstatic.net/stackoverflow/all.css");});
$("button.remove").on("click", function() { removeCSS("http://cdn.sstatic.net/stackoverflow/all.css");});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Hello</h1><div class="topbar"> <div class="icon-achievements"> <button class="add unread-count">Add</button> <button class="remove unread-count">Remove</button> </div></div>

Jquery - Adding and removing stylesheet on click

You don't have to remove a stylesheet completely from DOM: just disable it. It's easy to do, actually, but there are two things to be aware of:

$(function() {
var linkEl;
$(".css_switch").click(function() {
if (!linkEl) {
linkEl = $('<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />')
.appendTo('head')[0];
}
else if (linkEl.sheet) {
linkEl.sheet.disabled = !linkEl.sheet.disabled;
}
});
});

Demo. Each style link element has associated StyleSheet object, which can be disabled with, quite unsurprisingly, disabled property. But there's a caveat: the aforementioned object is created only when the external CSS document is loaded and parsed. Until this, linkEl.sheet is null; hence the check.

Note that simpler version:

else { linkEl.disabled = !linkEl.disabled; }

... works too (you change property of corresponding HTMLLinkElement, disabling it instead), but there's a subtle bug: this property can be changed even when the resource is not ready. So imagine a user clicking on the button, seeing no changes afterwards (CSS isn't loaded yet). Now they click the button again, this time disabling the link - and when the resource is there, it's not shown. A user is dazed and confused, and that's usually not good.

With the quoted version, disabling is done only when a user sees the result of CSS change.

How to change the href attribute for a hyperlink using jQuery

Using

$("a").attr("href", "http://www.google.com/")

will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:

<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>

...Then you probably don't want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute:

$("a[href]") //...

Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href, you might use something like this:

$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')

This will find links where the href exactly matches the string http://www.google.com/. A more involved task might be matching, then updating only part of the href:

$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});

The first part selects only links where the href starts with http://stackoverflow.com. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.

Disable/enable an input with jQuery?

jQuery 1.6+

To change the disabled property you should use the .prop() function.

$("input").prop('disabled', true);
$("input").prop('disabled', false);

jQuery 1.5 and below

The .prop() function doesn't exist, but .attr() does similar:

Set the disabled attribute.

$("input").attr('disabled','disabled');

To enable again, the proper method is to use .removeAttr()

$("input").removeAttr('disabled');

In any version of jQuery

You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:

// assuming an event handler thus 'this'
this.disabled = true;

The advantage to using the .prop() or .attr() methods is that you can set the property for a bunch of selected items.


Note: In 1.6 there is a .removeProp() method that sounds a lot like removeAttr(), but it SHOULD NOT BE USED on native properties like 'disabled' Excerpt from the documentation:

Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of "removing" them like their "attribute" counterparts in 1.5

add or remove css file from the page using jquery

You can simply use :not(:first) to exclude first link and remove rest

$("link[href*='http://wotfly.com/templates-common/106/css/newheader.css']:not(:first)").rem‌​ove();


Related Topics



Leave a reply



Submit