0

I have an app which allows the user to change the theme at runtime.

Before the new CSS is loaded, this code removes the old CSS:

jQuery('head > link').each(function () {
            if (this.href.includes('styles/kendo.')) {
                DOM.removeNode(this);
            }
        });

This looks OK to me, but when it runs, something gets broken (not sure what) and later CSS does not load properly.

If I comment out this code, then the CSS loads just fine. Makes no sense to me.

Maybe there is a completely different way to remove CSS from the DOM that would be better?

Greg Gum
  • 33,478
  • 39
  • 162
  • 233

2 Answers2

1

Have you tried document.styleSheets[i].disabled = true;?

This works in plain JS (no jQuery):

for (var i = 0; i < document.styleSheets.length; i++) {
  if (document.styleSheets[i].href.includes('styles/kendo.')) {
    document.styleSheets[i].disabled = true;
  }  
}

Another way in plain JS would be to use forEach:

[].forEach.call(document.styleSheets, function(element, index, array) {
  if (array[index].href.includes('localhost')) {
    document.styleSheets[index].disabled = true;
  }
});

(why .forEach starts with [] and uses.call is explained here)

This would be the jQuery version:

jQuery(document.styleSheets).each(function(i) {
  if (document.styleSheets[i].href.includes('styles/kendo.')) {
    document.styleSheets[i].disabled = true;
  }  
});

Here's some references on document.styleSheet, etc.:

Community
  • 1
  • 1
4lackof
  • 1,250
  • 14
  • 33
1

Everything looks fine in the code till

jQuery('head > link').each(function () {
            if (this.href.includes('styles/kendo.')) {

The next line DOM.removeNode(this); which is supposed to remove the HTML element i.e this uses DOM.removeNode method, it is not an inbuilt object hence we do not know how does it work, probably a library in your app might have that object so you may want to check its documentation.

Better than this if our task is to remove that particular HTML link element from the DOM we can use jQuery $.remove() method,

jQuery('head > link').each(function () {
            if (this.href.includes('styles/kendo.')) {
                $( this ).remove();
Deepak Kamat
  • 1,880
  • 4
  • 23
  • 38