Using JavaScript to scan a CSS file and identify any duplicate selectors

Exploring a scenario where I have a string containing CSS selectors, similar to the format below:

.u-br {
   blah blah
}

.u-tr {
    blah .blah
}

....
.u-mr { }

The task at hand is to validate the selectors (specifically the .u-tr part) to ensure there are no collisions or duplicates.

This process can be initiated as follows:

let selectorArray = process(stringOfCSS);

Upon completion of this step, the selector array should include:

['u-br', 'u-mr', etc]

Subsequently, it becomes crucial to verify that all entries within the array are unique, which can be achieved with existing methods.

Answer №1

Perhaps this solution could be of assistance to you. First, I am constructing an array containing the CSS rules from the initial stylesheet: document.styleSheets[0].cssRules.

Subsequently, I loop through the rules and if a rule starts with ".", I output it to the console. There is no necessity to check for the opening curly brace {. Hopefully, this will prove helpful to you.

let stylesArray = Array.from(document.styleSheets[0].cssRules);

stylesArray.forEach(rule =>{  
  if(rule.selectorText.substring(0, 1) == "."){console.log(rule.selectorText)}
})
.u-top-right {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}

.u-tr {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}
#test{display:none}

.test{display:flex;}

Answer №2

const styles = `.u-br, .u-nr {
    blah blah
}

.u-tr {
    blah .blah
}`;
const classes = styles.match(/\.-?[_a-zA-Z]+[\w-]*(?=[^{}]*\{)/g);

function checkForDuplicates(arr) {
    return (new Set(arr)).size !== arr.length;
}
console.log(checkForDuplicates(classes));//false;

//Identify the duplicate classes
var sorted_classes = classes.slice().sort();

var duplicates = [];
for (var i = 0; i < sorted_classes.length - 1; i++) {
    if (sorted_classes[i + 1] == sorted_classes[i]) {
        duplicates.push(sorted_classes[i]);
    }
}

console.log(duplicates);

Answer №3

To extract each classname individually, you can use a loop to search for them in the code. If a new classname is found, it will be added as a key to a variable called output, otherwise, the value of output[classname] will be incremented. Any value greater than 1 indicates a duplicate property.

let input = `.u-top-right {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}

.u-tr {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}.u-top-right {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}

.u-tr {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}.u-top-right {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}

.u-tr {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}.u-top-right {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}

.random-classname {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}`

const rgx = /\.(.+?)\s*\{\s*/,
  output = {}
let match
  
while((match = rgx.exec(input))){
  let classname = match[1]
  if(!output[classname]) output[classname] = 0
  ++output[classname]
  input = input.replace(rgx, '')
}

console.log(output)

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

Dynamic tables that reorganize when viewed on different devices

While working on a responsive website with Magento v1.8, I encountered a challenge in making the header responsive. I attempted using div but couldn't get it to work as expected. Switching to the table method has brought me halfway there, but I'm ...

How to align text to the right in a Bootstrap 5 card header

I'm facing an issue with a Bootstrap 5 card where I want to align certain content in the header to the right and some to the left. Despite my efforts, everything remains left-aligned. Here's a snippet of my code: <div class="card"& ...

Exploring MongoDB querying with two keys in conjunction with Express JS and NodeJS

I'm seeking assistance with my web application developed using Express JS and Node. I am encountering issues with the .find() command when trying to search for multiple words. It's interesting because using the $all command works when two words ...

Is there a way to trigger the second function once the first one has been completed?

When the change event occurs, I am invoking two functions. function1(); function2(); The function1() makes an ajax call. The function2() is running before function1() for some reason. Can anyone explain why this is happening? Any assistance would be ...

Storing and retrieving an HTML editable array using COOKIES in JavaScript

In my code, I have created an editable array where you can input student information. A button computes the grade for each student at the end of the line. Additionally, there are buttons to add rows for students and columns for different assignments. Now, ...

What is the best way to center a heading 2 element vertically within a div?

Can someone help me with aligning the h2 element vertically and horizontally in the center of the div? You can find my codepen here. html <div class="container"> <h2 class="center"> Hello World! </h2> </div> css: .c ...

React is having difficulty locating a specific module

I've been attempting to install the parallax library from https://github.com/wagerfield/parallax/. I have gone through the documentation and even found a sample usage in JavaScript. Planning to integrate it into React, based on the sample code and Rea ...

What is the best way to create multiple AngularJS applications using NodeJS?

Upon completing the tutorial found at https://docs.angularjs.org/tutorial, I was inspired to create a new application on my local machine using AngularJS and NodeJS as the server. To start this new project, I made a separate folder at the same level as th ...

Moving responsive table cell to a new line

Currently, I am faced with the challenge of embedding third-party content via dynamic means without any knowledge of Ajax or jQuery. My question is whether it's feasible to move a table cell onto a new line, essentially creating a new row. The embedd ...

Connect an external pure JavaScript file to my React component

Looking to create a dynamic react component with a festive birthday animation using an external javascript file. I've tried linking the external script like so: componentDidMount() { const script = document.createElement("script"); ...

Tips for capturing changes in a "count" variable and executing actions based on its value

I have a counter on my webpage and I'm trying to change the style of an element based on the count variable. I tried using the .change action but I haven't been able to get it working. It might not be the right solution. Can anyone provide some ...

Utilize JavaScript to extract data from an XML file through a specified

Hello, I am new to JavaScript, Currently, I am working on a project where I need to parse an XML File using JS and jQuery. Could you please advise on how to open an XML file based on its URL? var xml = "File.xml", xmlDoc = $.parseXML( xml ), $xml = $( x ...

What is the proper way to send a List of Strings containing key=value pairs to an Object?

As a newcomer to JavaScript, I am seeking a more efficient method for converting a list string into an object. The service provides me with the following list, but I require it in object form for processing purposes. For example: let objString = ['n ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

Tips for positioning Bootstrap thumbnail elements

I have a query regarding my implementation of the thumbnail feature in Bootstrap. My goal is to ensure that three thumbnails are aligned per row. Refer to the image linked below for clarification: This is the desired layout: (Click Here) The image illust ...

Keep elements in position when their bottom edge becomes visible while scrolling

This task may appear intricate, but I will do my best to explain it! I want to create a continuous scrolling article display similar to Bloomberg Politics (), but with a slight twist. My idea is to have the current article's bottom edge stick to the ...

Is it possible to use CSS transitions to animate an absolute positioned element?

I am having trouble getting a CSS transition to work for animating an element's position change. I have tried using the all properties in the transition declaration like in this example: http://jsfiddle.net/yFy5n/3/ However, my goal is to only apply ...

Utilize JavaScript and HTML to show error messages based on whether the user is deactivated or if the input is invalid

I need to show different error messages under the 'Email Address' input if the user is disabled and under the 'Password' input if the user is invalid. In my debugging process, I discovered that a user being disabled results in a "Status ...

The angular controller erroneously indicates that the modal form is valid even though it is not

I am currently working with a form that appears in a modal directive using bootstrap UI. The form consists of 2 input fields with html5 validation set to "required." Initially, in the controller, I tried to check if the form is valid before proceeding to ...

What is the best way to incorporate a horizontal scroll bar that remains fixed at the bottom of the screen?

Within my main container, I have a div that has a height fitting perfectly into the main container but a width wider than the main container with an overflow for the horizontal scroll bar. The challenge that I am facing is: 1. Instead of requiring the use ...