What is the method for uncovering classes that do not have any associated CSS selectors?

Take a look at this snippet of HTML code:

<style type="text/css">
.existing-class {
  background-color: #000;
}
</style>
<div class="existing-class non-existing-class"></div>

Within this code, there are two classes applied to the <div> element. The interesting part is that the class non-existing-class is not actually defined in the CSS on the page.

So, here's the question: How can a developer use programming techniques to identify elements on a webpage that are using classes which have not been defined in the loaded CSS?

Answer №1

Great job!😊
Make sure to pay close attention to the script I've put together, especially the getUndefinedClasses function.

function httpGet(theUrl) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", theUrl, false ); // synchronous request
  xmlHttp.send( null );
  return xmlHttp.responseText;
}


function getAllCSSClasses(cssdata) {
  var re = /\.(.+)\{/g;
  var m;
  let classes = [];
  do {
    m = re.exec(cssdata);
    if (m) {
      for(let key in m) {
        if(
           (typeof m[key] == "string") && 
           (classes.indexOf(m[key]) == -1) &&
           (m[key].indexOf(".") == -1)
          )
          classes.push(m[key].replace(/\s/g, " "));
      }
    }
  } while (m);
  return classes;
}

function getAllClasses() {
  var csses = document.querySelectorAll('link[rel="stylesheet"]'); 
   var classes = []
  for (i = 0; i < csses.length; ++i) {
    // let styledata = httpGet(csses[i].href);
    var styledata = ".hi{ display: none; }";
    var cclasses = getAllCSSClasses(styledata);
    var classes = Object.assign([], classes, cclasses);
    classes.concat(cclasses);
  }
  return classes;
}

function getHTMLUsedClasses() {
  var elements = document.getElementsByTagName('*');
  var unique = function (list, x) {
    if (x != "" && list.indexOf(x) === -1) {
        list.push(x);
    }
    return list;
  };
  var trim = function (x) { return x.trim(); };
  var htmlclasses = [].reduce.call(elements, function (acc, e) {
    return e.className.split(' ').map(trim).reduce(unique, acc);
  }, []);
  return htmlclasses;
}


function getUndefinedClasses(cssclasses, htmlclasses) {
  var undefinedclasses = [];
  for (let key in htmlclasses) {
    if(cssclasses.indexOf(htmlclasses[key])  == -1 ) {
       undefinedclasses.push(htmlclasses[key]);
    }
  }
  return undefinedclasses;
}

var cssclasses = getAllClasses();
var htmlclasses = getHTMLUsedClasses();

console.log("Undefined classes : " + getUndefinedClasses(cssclasses, htmlclasses))
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="hi there">
</head>
<body>
  <div class="hi"></div>
  <div class="there"></div>
  <div class="there_thier_333"></div>
</body>
</html>

Here's what has been accomplished:

  1. I extracted all the class names from the CSS data provided (you can pass the CSS data in various ways).
  2. Subsequently, I gathered all the classes utilized in HTML elements, storing them in arrays.
  3. Lastly, I identified and added the classes used by HTML Elements but not present in the cssclasses array, giving us the undefined classes in CSS.

(Access jsbin here for an example)

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

methods to locate the parent element of an element with selenium

<button class="wpO6b ZQScA" type="button"> <div class="QBdPU "> <svg aria-label="New Message" class="_8-yf5 " fill="#262626" height="24" viewBox="0 0 44 44" widt ...

The POST request did not yield an HttpResponse object; instead, it returned None

When I submit a selection from a dropdown form to views as a POST request, and then use this selection to query data from Django, I encounter an issue while trying to map Django models data to Highcharts following this approach. The error message "the view ...

The presence of parentheses in a JQuery selector

My database contains divs with ids that sometimes have parentheses in them. This is causing issues with my JQuery selector. How can I resolve this problem? Let me provide an example to illustrate: https://jsfiddle.net/2uL7s3ts/1/ var element = 'hel ...

What are the methods for storing scripts and images from my website?

Question on Website Speed I've been working on building a website hosted on x10hosting and have been researching ways to make it faster. I came across a page that suggested improving JQuery codes could help with site speed. The page mentioned that in ...

Hiding and securing a div element when JavaScript is disabled

My form includes a <div>. This particular <div> is a red circle. Even when JavaScript is disabled, it remains visible (I can use display: none to address this). The issue arises when I re-enable JS - upon user interaction, the <div> mov ...

"Utilize Angular's functionality to include labels for checkboxes generated using *ngFor directive

I am currently working with Angular 5 My goal is to generate multiple checkboxes using the code below and provide them with labels <input type="checkbox" *ngFor = "let v of options[0].options" [value]="1" [name] = "1"> Typically, when working with ...

TinyMCE evades the FreeMarker tags

Utilizing TinyMCE 4 as a WYSIWYG editor for HTML pages has been helpful. However, I have noticed that when integrating FreeMarker tag idioms like <#if condition>, <#else> in TinyMCE, they sometimes get distorted when switching between "code vie ...

Vue Template ref Error: Unable to access scrollHeight property of null object

I'm currently working on creating a responsive sidebar in Vue, and I encountered an issue after refactoring my project to remove the state.js file. The problem is related to the dropdown/collapse elements, and it's throwing a TypeError: Cannot re ...

Troubleshooting z-index conflict when using :before pseudo element to emphasize list entries

I am experiencing an issue with highlighting items in a list generated by JSTree using the :before pseudo element. The z-indexes seem to be causing some trouble, as adjusting them results in the highlighting appearing either behind all links or in front of ...

Determine the outcome with a PHP conditional statement for either "

I'm currently working on adding a function to a script where the user is prompted for a code, which I have successfully added. However, I am facing an issue in determining when to ask the user for the code and when not to. So, I believe I need to use ...

Different ways to adjust the appearance of table borders in HTML

I find myself at a standstill, hence why I am reaching out with this question. This Table presents itself with various border sizes and colors, along with similar complexities in the background of its cells. Could anyone provide me with guidance on how t ...

How can I convert a number to the format of hh:mm using Angular?

Within my form, there is an input field that should only accept numbers. Is it possible to format the input number into a hh:mm format once the user enters it? I prefer not to use input type = time. Do you have any suggestions for achieving this? ...

Is it possible for Websockets to receive data from Ajax requests?

I am currently working on creating a PHP and HTML5 websocket chat system. In this setup, one end will be a socket while the other end will be AJAX. Is it possible for PHP's socket_recv() function to receive data from sources like AJAX, MySQL, or any o ...

I'm struggling with organizing my webpage layout using CSS flexbox and CSS grid

Currently, I am working on creating a checkers game using HTML and CSS with the inclusion of CSS Flexbox and CSS Grid for layout design. However, I have encountered an issue where the page is not responsive vertically. When resizing the browser height in C ...

CSS animation stalling

While my angular app is loading all the necessary content through ajax, I display a loader on top of the content on a darker layer. The SVG used in this process contains an animateTransform: <svg width="38" height="38" viewBox="0 0 38 38" xmlns="http: ...

Utilizing jQuery to execute a particular task based on the selection of a radio button

I have implemented a few radio buttons using bootstrap, as shown below. <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary"> <input type="radio" name="options" id="option1"> Option 1 </label> <label cla ...

Leveraging Ajax to fetch JQuery

Currently, I am utilizing Ajax to trigger a PHP file for processing upon form submission. The JQuery form validation mechanism evaluates the variables' values to determine whether to proceed with submitting the form or to return false while displaying ...

Is there a reason why the integration of OnsenUI with Vue using vue-onsenui and v-ons-segment is not functioning

I am experiencing an issue with OnsenUI and VUE vue-onsenui v-ons-segment. Instead of displaying a button bar in a row as expected, I am seeing standard buttons. The problematic code resides in a customized Monaca CLI project utilizing the minimal VUE tem ...

Typescript input event

I need help implementing an on change event when a file is selected from an input(file) element. What I want is for the event to set a textbox to display the name of the selected file. Unfortunately, I haven't been able to find a clear example or figu ...

Setting the base font size for different screen sizes in Bootstrap 4 with responsive font sizing techniques

Using the Bootstrap gem in my Ruby on Rails application (version 4.3.1) has been a game changer. Recently, I stumbled upon the responsive font size functionality known as rfs, which was introduced in version 4.3 of Bootstrap. If you want to dive deeper in ...