Home > Net >  Loop through array and remove stylesheets
Loop through array and remove stylesheets

Time:10-10

I'm building a site in WordPress and the plugins come with a few unwanted css files.

I'm trying to remove these stylesheets via JS but encountering a Failed to execute 'querySelector' on 'Document': '0' is not a valid selector. error.

I'm trying to make it reusable so that I can add stylesheets to the array and remove easily, maybe even scripts too.

Unsure where I'm going wrong in my JS?

const assets = ["link[href*='/wp-content/plugins/js_composer/assets/css/js_composer.min.css']",
  "link[href*='/wp-includes/css/dist/block-library/style.min.css']"
]

for (var i in assets) {
  var cssElement = document.querySelector(i);
  cssElement.disabled = true;
  cssElement.remove();
  console.log(cssElement);
}

CodePudding user response:

First of all, the i in your for .. in loop holds the index of the item at the current iteration, so on the first iteration, i will be equal to 0. So to get the selector from you selector array, at each iteration, you'd need to pass assets[i] to the quesrySelector method.

Another thing, at every iteration, you should check if querySelector has found an element or not before trying to remove the expected element.

const assets = [
  "link[href*='/wp-content/plugins/js_composer/assets/css/js_composer.min.css']",
  "link[href*='/wp-includes/css/dist/block-library/style.min.css']"
];

let cssElement;

for (var i in assets) (cssElement = document.querySelector(assets[i])) && cssElement.remove();
/** the above line will only executed when "querySelector" has found an element on the page */

Another possible way to have the same effect is to use the forEach method:

const assets = [
  "link[href*='/wp-content/plugins/js_composer/assets/css/js_composer.min.css']",
  "link[href*='/wp-includes/css/dist/block-library/style.min.css']"
];

let cssElement;

assets.forEach(s => (cssElement = document.querySelector(s)) && cssElement.remove());

Learn more about the forEach method.

CodePudding user response:

Use for of not for in. i in your case is the index but you want it to be the element in the array.

The error is saying that you passed 0 (which is the first index) to the querySelector which is not a valid DOM element

CodePudding user response:

const assets = ["link[href*='/wp-content/plugins/js_composer/assets/css/js_composer.min.css']",
  "link[href*='/wp-includes/css/dist/block-library/style.min.css']"
]

for (var i in assets) {
  var cssElement = document.querySelector(assets[i]);
  cssElement.disabled = true;
  cssElement.remove();
  console.log(cssElement);
}
<link href="/wp-content/plugins/js_composer/assets/css/js_composer.min.css" rel='stylesheet'/>
<link href="/wp-includes/css/dist/block-library/style.min.css" rel='stylesheet'/>

  • Related