Identifying all unused CSS class selectors in the code that do not have any CSS rulesets assigned

Is there a way to retrieve a list of all the CSS classes I have used in my code that do not have a corresponding "CSS ruleset" defined for them?

For example:

/*Definition (or Rule set) for .some-random-class 
        doesn't exist or is commented out like below

        .some-random-class {
          width: 100vw;
          height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
        }

      */

      .known-class {
        background-color: red;
        width: 100px;
        height: 100px;
      }
<div class="some-random-class">
        <span class="known-class"/>
      </div>

I am hoping for a function such as getAllUndeclaredCSS() to provide the output ['some-random-class'].


Update 1: This is different from determining which CSS styles are actively being used, as I am looking for instances where the definitions are missing but the classes are being utilized.

Update 2: I currently have a basic solution to get me started. It may not cover all cases, but it works to some extent.

Answer №1

I found the solution to my problem!

let elementsWithClass = document.querySelectorAll("[class]");
let classNames = new Set();
elementsWithClass.forEach(node =>
    node.classList.forEach(item => classNames.add(item))
);

let stylesheets = document.styleSheets;
let definitionsFound = new Set();
for (i = 0; i < stylesheets.length; i++) {
    rules = stylesheets[i].cssRules;
    for (j = 0; j < rules.length; j++) {
        if (rules[j].type === CSSRule.STYLE_RULE) {
            let match = rules[j].selectorText.match(/\.[^\.: ]+?(?=\.| |$|:)/g);
            match && match.forEach(item => definitionsFound.add(item.replace(".", "")));
        }
    }
}

let missingDefs = [];
classNames.forEach(item => {
    if (!definitionsFound.has(item)) {
        missingDefs.push(item);
    }
});
console.log(missingDefs);

Try running this code on your website to identify any missing CSS rules. Many thanks to @SalmanA for sharing this helpful tip!

PS: If you encounter issues using the Set in older browsers, you can switch it back to an array and remove any duplicates.

Answer №2

Why not give this a shot?

:not([class])

This simple syntax will specifically target elements with no assigned CSS classes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance user experience with AngularJS Bootstrap autocomplete feature by automatically filling input box when hovering over dropdown options

I am currently implementing the AngularJs Bootstrap typeahead functionality. Typically, when we enter text that matches an option, the dropdown list appears. https://i.stack.imgur.com/395Ec.png What I aim for is to automatically fill the textbox with the ...

Tips for customizing the appearance of path elements within an external SVG file being utilized as a background image

How can I change the color of the paths in an SVG background image assigned to a div using CSS? ...

Styling links conditionally in a React component

How can I style the page title in my nav bar when I am on the selected path? I am using React and Tailwind CSS. For example, I want the title to turn yellow when I am on the current page. Here is the logic I have tried, but it doesn't seem to be work ...

What is the best way to adjust the position of a dropdown menu in Material UI?

I am currently working on a Gatsby application and I'm trying to achieve a dropdown menu effect when the Menu icon is clicked, with the menu appearing right under the header and expanding to 100% width. Below is the code snippet that I have been using ...

Troubleshooting: Issues with Jquery's replaceWith function

I'm facing an issue with a table I have that includes a button in one of its columns. The button is supposed to toggle the class of the current row in the table and then replace itself once clicked. $(document).ready(function() { $(".checkOut"). ...

Tips for utilizing CSS selector path in Selenium to extract a particular attribute from a span class in Python

I need help retrieving the title attribute from the span class = g47SY lOXF2, but I am struggling to locate the correct CSS path. This is what I have attempted: Title = self.browser.find_element_by_css_selector('ul li a span').get_attribute(&apo ...

Boxes not occupying entire vertical space

My structure is unique, like a 9-box with div elements: <div class="NBWrapper"> <div class="NBTopRow"> <div class="NBLeft" /> <div class="NBRight" /> <div class="NBMiddle" /> </div> & ...

Error: Media queries must always start with a parenthesis

I couldn't sleep because of this issue, guys. Here is a snippet of my problematic code: <style lang="scss" scoped> @import '~/assets/scss/main.scss' .home_nav{ nav { } } </style> The error ...

Is it possible to apply the box-shadow effect only to the left and right sides of a div?

Looking to achieve a box shadow effect on just the left and right sides of a div? box-shadow: 0px 0 20px rgba(0,0,0,.4); I experimented with variations like: box-shadow: 0, foo, 0, foo; but it did not yield the desired results. In the illustration bel ...

Is there a way to prevent the text next to these FontAwesome icons from moving whenever the icon itself changes?

I am currently working on creating a unique custom checkmark using FontAwesome in my project. Below is the snippet of HTML and CSS style code that I am using: .check { font-size: 1.25rem; cursor: pointer; } .check-unselected { color: #4E44 ...

I'm unsure of how to eliminate the border outline on this particular text area

The textarea has an unwanted blue outline, and despite trying outline:none; in the CSS, it's still there. See the code below: #floatingTextarea { border: none; outline: none; } <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/ ...

Bootstrap allows for the use of video backgrounds, offering the option for borders to be included

Having trouble with a Bootstrap HTML page featuring a video background? The issue is that sometimes the video has borders on the left and right, and occasionally on mobile devices as well. Oddly enough, when the browser (Chrome or Firefox) is refreshed, th ...

The tooltip being displayed is plain and lacks any design elements

When I hover over my a element, only a simple tooltip appears without any styling, unlike what is shown in the Bootstrap documentation. (I am creating the a element using JavaScript) HTML <!DOCTYPE html> <html lang="en"> <head> ...

resizing problem with images that adapt to different screen sizes

I've been working on creating a responsive website, but I'm having trouble with the resizing of the two background images I added to the header. When I view the site on a mobile device, the header appears squashed. I think this might be because I ...

Leveraging the power of React in conjunction with an HTML template

After purchasing an HTML template from theme forest, I am now looking to incorporate React into it. While I find implementing Angular easy, I would like to expand my skills and learn how to use React with this template. Can anyone provide guidance on how ...

WordPress WooCommerce causing the right bar to be pushed below

I'm currently facing an issue on my WordPress site with a purchased template and Woocommerce integration. The problem lies in the fact that the right sidebar gets pushed down on the shop page. When I reached out to the template developers, they sugges ...

Using the `document.querySelector` method to target the `.mat-progress-bar-fill::after` element

Is there a way to dynamically adjust the fill value of an Angular Material Progress Bar? In CSS, I can achieve this with: ::ng-deep .mat-progress-bar-fill::after { background-color: red; } However, since the value needs to be dynamic, I am unable to do ...

Using jQuery to automatically scroll to the bottom of a div when sliding down

When a user clicks on a link to slide the div down, I want it to automatically scroll to the bottom of the div. I've attempted to use scrollTo and animate methods to achieve this effect. $('html, body').animate({ scrollTop: $("#elementID") ...

Is it possible for a media query to target only 2 elements instead of all 3?

Currently, I am dealing with an older website for a client, and it appears that a media query is not correctly affecting three specific classes out of the total. These problematic classes are .free-ship, .wholesale, .chronicles The CSS styling for these c ...

Manipulating Objects with CSS Transform in Global/Local Coordinates

If we take a closer look at our setup: <div id="outside"> <div id="inside">Foo</div> </div> and apply a rotation to the outer element - let's say turning it 45 degrees clockwise: <div id="outside" style="transform: ro ...