Loop through array and remove stylesheets

Issue

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

Solution

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.

Answered By – ths

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published