1

I got a line on the top of the page,

<link rel="stylesheet" href="style/style.css">

How do I remove it by jQuery or javascript?

Tired this way,but not working

$(link['style/style.css']).remove();
olo
  • 5,225
  • 15
  • 52
  • 92

4 Answers4

2

jQuery selection by attribute is in this format:

$('link[href="style/style.css"]');

Then you need to disable it:

// prop() suggestion from @jahroy
$('link[href="style/style.css"]').prop("disabled", true);

The docs

SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59
  • Slow down the downvote train. This is the correct way to do it. Selection by attribute is in the format I have given. Check the docs. – SomeShinyObject May 23 '13 at 01:39
  • Shouldn't you use [jQuery.prop()](http://api.jquery.com/prop/) [in stead of _attr()_] to disable the link? By the way, I did **not** downvote. From the docs: "_The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value._" – jahroy May 23 '13 at 01:41
  • @jahroy, that would be better, huh? I fixed it. Thanks for the reminder. – SomeShinyObject May 23 '13 at 01:44
  • why don't remove it by $('link[href="style/style.css"]').remove()? – Stiger May 23 '13 at 01:46
  • @Stiger, apparently it doesn't work that way from what I have read. `remove()` takes away the element but that stylesheet information is still there. – SomeShinyObject May 23 '13 at 02:03
2

In most modern browsers you can iterate through the list of stylesheets and disable the ones you want:

var toRemove = 'style/style.css';

[].forEach.call(document.styleSheets, function(styleSheet) {
    if (styleSheet.href && styleSheet.href.substr(-toRemove.length) === toRemove) {
        styleSheet.disabled = true;
    }
});
Ziad
  • 1,036
  • 2
  • 21
  • 31
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

This is not a direct answer to your question but it may be a better way to achieve what you are trying to do:

If you are controlling the stylesheet and you want an easy way to turn it on and off then you may consider using the same trick that is used by Modernizr. Instead of having in your stylesheet:

.some-class { color: red }

and then removing the entire stylesheet it in some cases, you can have:

.style-x .some-class { color: red }

and then in your HTML or JavaScript you can add "style-x" class to the body tag:

<body class="style-x">
  [...]
  <div class="some-class">red text</div>
  [...]
</body>

Removing the style in JavaScript is just removing the class style-x from the body tag, using .className in plain JavaScript or .removeClass() in jQuery.

That way you can have many "styles" in one concatenated and minified CSS file that can be activated and deactivated independently.

rsp
  • 107,747
  • 29
  • 201
  • 177
0

This javascript snippet works

how to remove css rel by javascript or jQuery

document.styleSheets[0].disabled = true;
Community
  • 1
  • 1
olo
  • 5,225
  • 15
  • 52
  • 92