You are here:Home»KB»Programming»Javascript»Removing or replacing a CSS stylesheet with JavaScript/jQuery
Friday, 11 December 2015 15:45

Removing or replacing a CSS stylesheet with JavaScript/jQuery

Written by

There are several ways to unload CSS and JS scripts that have already been applied by using Javascript or JQuery. To unload CSS is simpler than JS because for JS it depends on whether the JS has been triggered and if it has already altered the DOM with it' payload, because once the DOM is altered, disabling the JS might not return the DOM it to it's original state, if that is not a problem do not worry.

General Notes

You must follow the rules below:

  • Use the full filepath to the file when using href
  • Make sure there is a slash at the beginning of a href statement when using a file path, i.e. all file paths except when you are using just the filename. I could not get my script to work withou the slash at the begining.
  • When working with jQuery in Joomla you must use jQuery() instead of $()

Depending on what type of scripting language you use, Javascript/JQuery, to unload the CSS or JS there are different ways of referencing the elements.

You can access the relevant element by:

  • Physical file path
  • href location of the file
  • Stylesheet/Script name
  • Numeric occurance of a tag type (ie the 3rd occurance of the <link> tag)
  • element id - If this is set

Identifiers

These are different identifiers you can use in the following codes to basically identify which file or element you want to work on. There might be more and should be easy to experiment with:

  • [href="fileToRemove.css"]  -  Match the file fileToRemove.css , the file needs to be in the same directory as the script
  • [href="/templates/jsn_time_pro/ext/k2/jsn_ext_k2.css"]  -  Match the file /templates/jsn_time_pro/ext/k2/jsn_ext_k2.css
  • [href*='baz']  -  href has some code in it, and then baz (not checked this)
  • [href~="foo.com"]  -  This matches all href with foo.com anywhere in it (not checkedd this)
  • [title="mystyle"]  -  The element title is mystyle
  • [src="<path>"]  -  A file that has this filepath (obviously swap <path> for the file path)
  • [id="disableme"]  -  The element's id is disableme

The points at which I can activate the unload script:

  • An inline script
  • 'On Page Load' trigger
  • After the target CSS or JS has loaded as an external script
  • On 'DOM ready' trigger

If using jQuery you must run the script after you load the jQuery library.

JQuery Solution

Although these are all written for CSS, the commands should work for Javascript script calls. These scripts will not run unless they are run after the page has loaded the JQuery library.

" and ' can be interchanged but i prefer to use " for normal HTML declarations. This keeps things easy to understand.

These changes will be applied to the DOM so when you are looking at the source of the page you might not see them, it depends on the browser. If in doubt use the Web Developer Toolbar in Firefox and select View Generated Source and you will see the source code with all changes applied by the javascript.

It is important to use .prop, not .attr. If you use .attr, the code will work in some browsers, but not Firefox. This is because, according to MDN, disabled is a property of the HTMLLinkElement DOM object, but not an attribute of the link HTML element. Using disabled as an HTML attribute is nonstandard.

Disable CSS

$('link[href="mycustom.css"]').prop('disabled', true);

This will disable the mycustom.css although for most purposes the CSS file has been removed, but this CSS file can be re-enabled. When you look at the generated souce you will see that the link for mycustom.css is still present butthe styling is not applied.

Re-Enable CSS

$('link[href="mycustom.css"]').prop('disabled', false);

Re-enable a mycustom.css CSS file.

Remove CSS

$('link[href="mycustom.css"]').remove();

This will completely remove the the mycustom.css from the DOM, the page will need to be refreshed without this script on it to load the CSS file. when you look at the generated source code you will see a blank line where the mycustom.css link use to be, almost like a placeholder.

Insert CSS

$('head').append('<link href="/mycustom.css" rel="stylesheet" id="newcss" />');

This command will insert the mycustom.css CSS file into the header. The id="newcss" is optional but can be useful.

Insert CSS 2

This is another version to insert a CSS file from - How to load CSS stylesheets dynamically with jQuery | Vidal Quevedo

$('head').append($('<link rel="stylesheet" href="/mycustom.css" type="text/css" media="screen" />'));

This command will insert the mycustom.css CSS file into the header. The instructions are simple and well layed out but I dont know why there is a second $().

Remove a CSS file from Joomla via an Inline Script

joomla has JQuery inbuilt which makes things easier

I have the need to remove a CSS file (jsn_ext_k2.css) from joomla on a single page but without altering any core code or extension. So I will need to do this by an inline script as i do not want to load the script site wide.

noConflict()

Joomla runs JQuery in noConflict() mode because it uses other libraries so instead of calling a function with a $() you should use jQuery() , make note of the capitalised Q.

Joomla loads the noConflict() from http://yoour-joomla-site.com/media/jui/js/jquery-noconflict.js

If you do not use the correct format for the jQuery function you are likely to see either of the following errors:

  • TypeError: $(...) is null
  • TypeError: $(...).ready is not a function

The CSS is called by the following:

<link rel="stylesheet" href="/templates/jsn_time_pro/ext/k2/jsn_ext_k2.css" type="text/css" />

I have removed the CSS file by using the following inline code:

<script type="text/javascript">
	jQuery('link[href="/templates/jsn_time_pro/ext/k2/jsn_ext_k2.css"]').remove();
</script>

This Also works but by disabling the CSS file

<script type="text/javascript">
	jQuery('link[href="/templates/jsn_time_pro/ext/k2/jsn_ext_k2.css"]').prop('disabled', true);
</script>

Things i have used:

  • The full relative path
  • A slash at the beginning of the relative path, without it, the script will not remove the CSS
  • jQuery() instead of $()
  • .remove() because I do not need the CSS file anymore

Code Examples

Unload CSS from webpage - Stack Overflow

document.getElementsByTagName('link')[0].disabled = true;
  • This references the first link element by its position (i.e. 0)
$("link[href='fileToRemove.css']").remove();
  • This references the stylesheet by its name which is better and more precise
  • Obviously, replace fileToRemove.css with the relative path and filename of the file to be unloaded.
  • I had to put the filename in quotes to make it work e.g. $("link[href='test.css']").remove();
  • If you don't want to put the path, you can add a * before equal sign. $("link[href*='fileToRemove.css']").remove();
var firstLink = document.getElementsByTagName('link')[0];
firstLink.parentNode.removeChild(firstLink)
  • This would remove the first link element on the page - not sure how your html is structured but I'm sure you can use it as an example. You might want to check the type attribute if it's 'text/css' and you're targeting the right media (screen), or possibly check if the href contains 'css' anywhere if you have other link elements that aren't css references.
  • Note you can also re-set the href attribute to point to a non-existing page instead of removing the element entirely.
  • It's uncommon to see the id attribute set on the link element but I'm sure for this exact purpose the OP would probably want to, less parsing and dealing with multiple link elements.

How to unload a css file using only its filename? - Stack Overflow

I have a css file in my <head> tag, defined as follows:

<link href="/foo/bar/baz.css" rel="stylesheet" class="lazyload" type="text/css">

I want to be able to remove this css file dynamically, from the javascript. However, at runtime, I won't have the full href available, only the baz.css part (That's because the file is hosted at a CDN, and the url can be dynamically generated / different each time, so it can't be hard-coded).

$("link[href*='baz']").prop('disabled', true);
$("link[href*='baz']").remove();

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

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.

document.styleSheets[0].disabled = true;

//so in your case using jquery try

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

These days, the "jQuery way" would look like

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

I managed to do it with:

$('link[title="mystyle"]').attr('disabled', 'disabled');

it seems this is the only way to remove the styles from memory. then I added:

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

to remove the element too.

To disable your selected stylesheet:

$('link[title="mystyle"]').prop('disabled', true);

If you never want that stylesheet to be applied again, you can then .remove() it. But don’t do that if you want to be able to re-enable it later.

To re-enable the stylesheet, do this (as long as you didn’t remove the stylesheet’s element):

$('link[title="mystyle"]').prop('disabled', false);

In the code above, it is important to use .prop, not .attr. If you use .attr, the code will work in some browsers, but not Firefox. This is because, according to MDN, disabled is a property of the HTMLLinkElement DOM object, but not an attribute of the link HTML element. Using disabled as an HTML attribute is nonstandard.

To remove a stylesheet:

$('link[src="<path>"]').remove();

To Replace a stylesheet:

$('link[src="<path>"]').attr('src','<NEW_FILE_PATH>');

no jQuery solution

if you can add id to your link tag

<link rel="stylesheet" href="/css/animations.css" id="styles-animations">

document.getElementById("styles-animations").disabled = true;

if you know index position of your css file in document

document.styleSheets[0].disabled = true; // first
document.styleSheets[document.styleSheets.length - 1].disabled = true; // last

if you want to disable style by name you can use this function

/**
 * @param [string]  [styleName] [filename with suffix e.g. "style.css"]
 * @param [boolean] [disabled]  [true disables style]
 */
var disableStyle = function(styleName, disabled) {
    var styles = document.styleSheets;
    var href = "";
    for (var i = 0; i < styles.length; i++) {
        href = styles[i].href.split("/");
        href = href[href.length - 1];

        if (href === styleName) {
            styles[i].disabled = disabled;
            break;
        }
    }
};

note: make sure style file name is unique so you don't have "dir1/style.css" and "dir2/style.css". In that case it would disable only first style.

Removing the CSS file - Stack Overflow

Give an id to the <link> tag.

<link rel="stylesheet" href="/style1.css" id="style1" />
<link rel="stylesheet" href="/style2.css" id="style2" />

And use this code:

$("#A").click(function(){
    $("#style1").attr("disabled", "disabled");
});

Note: While there is no disabled attribute in the HTML standard, there is a disabled attribute on the HTMLLinkElement DOM object.

The use of disabled as an HTML attribute is non-standard and only used by some Microsoft browsers. Do not use it. To achieve a similar effect, use one of the following techniques:

  • If the disabled attribute has been added directly to the element on the page, do not include the <link> element instead;
  • Set the disabled property of the DOM object via scripting.

You can unload a css by disabling it as follows:

$("#A").click(function(){
    $("link[href*=bb.css]").attr("disabled", "disabled");
    $("link[href*=cc.css]").attr("disabled", "disabled");
    $("link[href*=aa.css]").removeAttr("disabled");
});

How to dynamically remove a stylesheet from the current page - Stack Overflow

Is there a way to dynamically remove the current stylesheet from the page?

For example, if a page contains:

<link rel="stylesheet" type="text/css" href="http://..." />

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();

According to this question, just removing the link element is not enough. You should make it disabled first, with .prop('disabled', true). Though it’s possible that browsers have changed since that question was written (2010), and you don’t need to disable the link

If you know the ID of the stylesheet

use the following. Any other method of getting the stylesheet works as well, of course. This is straight DOM and doesn't require using any libraries.

sheet = document.getElementById(styleSheetId)
sheet.parentNode.removeChild(sheet)

 Other Links

Read 32372 times Last modified on Saturday, 12 December 2015 20:16