Originally posted by NickFitz
View Post
Have you tried something like:
Removing all styles is probably a bit drastic for what you want though, so if you just want one then do something like:
or, better still, set an id attribute (for just one) or a class (for several), and use the appropriate argument to querySelector (for one) or querySelectorAll (for several), or of course getElementById and getElementsByClassName. Note that querySelectorAll returns a node set, not an array, so you can't call methods like forEach directly on it - you have to do the [].forEach.call dance instead. Or, if you don't like array comprehensions, you can just do a good old-fashioned for loop to iterate over the node set, as it does have a length property.
IIRC you can also do something like
and the new styles will be loaded, replacing the old. How reliable that is in crap like IE<10, I don't know. (I used to, but I've forgotten.)
As always, test in the various browsers you expect to support before rolling it out to production; though the feature check for querySelectorAll should insulate you from ones that won't understand any of it
Oh, and IIRC, getElementsByClassName will return a live node set (i.e. it reflects changes in the document) so you'll need to iterate over it backwards if you're removing any, as they'll disappear from the node set at the same time as they disappear from the document
Code:
// only do stuff for reasonably up-to-date browsers
if (document.querySelectorAll) {
// get all <link> elements of type text/css
var links = document.querySelectorAll("link[type='text/css']");
// remove all CSS
[].forEach.call(links, function(link) {
link.parentNode.removeChild(link);
});
}
Code:
var linkToMessWith = document.querySelector("link[type='text/css'][href='http://example.com/styles/get-rid-of-this.css']");
linkToMessWith.parentNode.removeChild(linkToMessWith);
IIRC you can also do something like
Code:
document.getElementById("someCss").href = "/styles/new-styles.css";
As always, test in the various browsers you expect to support before rolling it out to production; though the feature check for querySelectorAll should insulate you from ones that won't understand any of it

Oh, and IIRC, getElementsByClassName will return a live node set (i.e. it reflects changes in the document) so you'll need to iterate over it backwards if you're removing any, as they'll disappear from the node set at the same time as they disappear from the document


Leave a comment: