identifying unused class names within an HTML codebase

Is there a way or tool available for detecting unused class names in HTML code?

I have some HTML code with old Bootstrap, jQuery, and personalized CSS styles like below:

<div class="clear fot-her likes tab-sub">content</div>

But I need to identify and remove any unused classes. If the fot-her class does not apply any style, I want to add it to a list and display an alert.

I found this, but it only retrieves the element's computed style:

var style = window.getComputedStyle(element [, pseudoElt]);

And this fetches elements by class name only:

var elements = document.getElementsByClassName(names);

Script:

function checkClassCSS() {
    let doc = document.all;
    let style = document.styleSheets;
    var listOfClasses = []
    Object.entries(doc).forEach(([key, element]) => {
        let classes = element.className.split(/\s+/);
        let new_classes = []
        classes.forEach((cl) => {
            if (cl != '') {
                new_classes = new_classes.concat(['.' + cl]);
            }
        });
        listOfClasses = listOfClasses.concat(new_classes);
    });
    listOfClasses = listOfClasses.filter(v => v != '');
    listOfClasses = Array.from(new Set(listOfClasses));
    var selectorClass = []
    Object.entries(style).forEach(([key, node]) => {
        let rule = node.cssRules;
        Object.entries(rule).forEach(([key, cssSelector]) => {
            selectorClass = selectorClass.concat([cssSelector.selectorText]);
        });
    });
    selectorClass = selectorClass.filter(v => v != '');
    selectorClass = Array.from(new Set(selectorClass));
    var missing = [];
    listOfClasses.filter(function(x) {
        if (!selectorClass.includes(x)) {
            missing.push(x);
        }
    })
    console.log(missing);
}

I am having trouble correctly identifying unused class names. For example, col-lg-4 may be used in the HTML code but still appears in the missing variable.

Answer №1

Searching for document.all and checking for tagName=="STYLE".
Within those elements (if any), examining sheet.cssRules and retrieving each selectorText.
These are the expected classes - gather them into an array.
Next, scanning through all other document.all items, searching for classList.
Comparing them to the array - if found in the array, great, if not: alert.
Best of luck!

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

Challenges with conflicting CSS styling issues

I am facing a CSS issue on my website. I am trying to add captions for images on my site. I have experimented with the jquery-capty plugin () and some custom CSS styles for framed images (). While both solutions work in my regular layout, they do not funct ...

A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code: async run(minutesToRun: number): Promise<void> { await authenticate(); await this.stock.fillArray(); await subscribeToInstrument(this, this.orderBookId); await subscribeToOrderbook(this, this.orderBookId ...

Passing console.log as an argument in a JavaScript abstraction

Hey amazing minds of the coding world! I've embarked on a journey to learn JavaScript and I'm currently immersing myself in the Eloquent JavaScript book! At the moment, I am working on abstracting a for loop action with this code snippet... fu ...

What is the reason for the Express middleware using parenthesis syntax, whereas custom-made middleware does not?

What is the reason behind Express inbuilt middleware using a parenthesis syntax like app.use(express.json()) while custom-made middleware does not use parentheses like app.use(logger)? It seems to throw an error with parentheses. I'm uncertain if th ...

Footer content is displayed at the center of the page before anchoring itself to

Looking for some assistance here. Every time I refresh the page or open it anew, the footer oddly pops up in the middle before swiftly moving back down to the bottom where it belongs. It's quite bothersome and despite my best efforts, I haven't b ...

Instructions for using jQuery to replace the final <a> tag within a specific section

Here is a section that I am working with: <section class="breadCrumb"> <a href="/">Home</a> <span class="divider">&gt;</span> <a class="CMSBreadCrumbsLink" href="/SCCU.Stg/Events-Calendar.aspx">Events Calendar ...

Incorporating a Menu within a TableCell using Material-UI

I have a desire to incorporate Google's Material UI Menu Item inside a TableCell, following their documentation guidelines here in this illustration: https://i.stack.imgur.com/IffEM.png This is my current method: import React from 'react' ...

The created hook does not execute when navigating to the same route with a different query parameters

One of my components has a created hook set up as follows: created() { if (this.$route.query.q) { //fetchdata } } But, when I try to change the URL within the same component using $router.push(`?q=${search}`), the URL updates but the creat ...

Retrieve JSON data sent via AJAX request in a Rails controller

I recently sent an ajax post request to receive json data, but I'm struggling to access that data in my rails controller. How can I properly retrieve this information? Below is the code snippet of how I posted the data using ajax: jQuery.ajax({ ...

Using Vue components in a TypeScript file

I recently started using Vue.js with TypeScript and stumbled upon this GitHub repository. While working on it, I encountered an issue where I received an error while trying to import a Vue Single Component File from TypeScript. My development environment ...

How can MongoDB insert a field that corresponds to a JavaScript variable?

I'm having trouble adding a new field to MongoDB. The database accepts my Javascript variable as data, but not as the name for the new field: function appendInformation(question, answer) { Sessions.update({ _id: Id }, { question : answer }); } T ...

Having trouble selecting the clicked element after a successful Ajax call, especially when there are multiple elements with the same name

When dealing with multiple elements that share the same class name, I am attempting to target the 'clicked' element upon a successful Ajax return. <td data-name='tom' class="status"><a href="">click< ...

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

Mastering the art of navigating through multiple nested objects is achievable by harnessing the power of recursive

I'm utilizing the AngularTree directive in my Angular application to display a tree view of a specific data structure. The data structure can be viewed at https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/. You can find more information about the Angul ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

Utilizing a Variety of Animations with D3 (version 5)

I am currently working on an animation that involves fading out text in a list and collapsing the list when the heading is clicked. However, I am facing a few issues with the code provided in this example. d3.select('.panel-heading') .on(&apos ...

Tips for concealing labels until the submit button is activated

I am currently handling a project involving a Spring Controller and JSP. Within a JSP page, I have included a button labeled Process. Upon clicking this button, two radio buttons are displayed below it along with a Submit button. After tapping the Submit ...

Using Bootstrap for Fixed Headers and Section Anchors

Despite my best efforts, I am struggling to resolve an issue with my fixed bootstrap navbar and internal links. I have experimented with various solutions, including using a JavaScript onscroll event listener and applying styles directly in the markup. How ...

Generate a new entry for a singular piece of data within an array

I am working on a matchmaking system where two players of the same level are matched and joined in one array. My goal is to include a second data in the array for players who do not have a match. Example: EntryID: “15”, player: ”testing11”, level: ...

Get rid of the title on Superfish Menu in Drupal 7

Exploring Drupal for the first time, I've been able to find solutions to all my queries except one - removing the "Main Menu" header from my superfish menu. The region called superfish has successfully had superfish added to it, but I'm unable t ...