Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values.

     table[my-type="myStyle"] {
        width: 255.388px !important;
    }

This code snippet is included in numerous CSS files within my style directory.

Answer №1

Utilizing postcss can help you extract the desired values from CSS.

Below is a sample code snippet to retrieve the minimum and maximum widths from various CSS files (using the selector table[my-type="myStyle"]):

const fs = require('fs');
const postcss = require('postcss');

const allWidthValues = [];

const files = [
    'styles/style-1.css',
    'styles/style-2.css',
    'styles/style-3.css'
];

const selector = 'table[my-type="myStyle"]';

const processor = postcss.plugin('processor', () => (css) => {    
    // Iterate through each rule node.
    css.walkRules((rule) => {        
        // Check for matched selector 
        if (rule.selector.indexOf(selector) !== -1) {
            // Iterate through declarations.
            rule.walkDecls(decl => {
                // Extract width declaration
                if(decl.prop.indexOf('width') !== -1) {
                    const width = decl.value.replace('px', '') * 1;
                    allWidthValues.push(width);
                }
            })
        }
    });
});

files.forEach(file => {
    const css = fs.readFileSync(file, 'utf-8');
    postcss([processor])
        .process(css, {from : file})
        .then(() => console.log('Successfully processed file : ', file))
        .catch(() => console.log('Error processing file : ', file));    

});

console.log('All extracted width values : ', allWidthValues);

allWidthValues.sort();

console.log('Minimum width : ', allWidthValues[0]);
console.log('Maximum width : ', allWidthValues[allWidthValues.length - 1]);

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

Web fonts are functioning properly only on Chrome and Safari for Macintosh operating systems

A web designer provided me with some fonts to use on a website. Below is the content of my fonts.css file: /* Font Awesome */ /* Font Awesome Bold */ @font-face{ font-family: 'font-awesome'; src: url('fonts/font-awesome-bold-webf ...

styled components are having issues with background gradients and opacity not functioning properly

Hello, I am currently working with styled components and have the following global style code: const GlobalStyle = createGlobalStyle` html{ font-family: roboto; background: linear-gradient(45deg,rgba(137,255,255,0.5),rgba(161,252,143, 0 ...

The process of sending files through the multer function within a controller has many steps that need

I am currently implementing an MVC design pattern. My goal is to upload a csv file to a local folder path and then upload the filename to a MySQL database. The issue I am facing is that, despite successfully uploading the file and saving it in my folder, t ...

Inquiring about the status of uploads in the AjaxFileUpload to ensure files have been successfully uploaded

How can I check if the file selected in AjaxFileUpload has already been uploaded or is pending? For example: https://i.stack.imgur.com/q6qUQ.png I want to validate files that are still pending upload. Here is my .aspx page code <form id="form1" runa ...

Error: Unable to delete item because the delItemRow function is not defined for this.props

No matter what I try, I can't seem to get the delete functionality to work on my React TO-DO list. I've spent all day attempting different methods but have had no success. It seems like I'm missing something, and I just can't figure out ...

What is the best way to find out the hosting locations of npm packages?

I'm currently facing some challenges while attempting to install npm packages on a restricted Internet-access machine. I can request permission from the network team for access to a remote host/port, but I am unsure about the specific hosts/ports that ...

Mantine UI: Elevate Your Component Library Experience

I am in the process of creating a Component library for internal company projects, which will be packaged as an npm package. To kick things off, I am starting with Mantine and plan to incorporate customization using tailwind CSS. As a test, I have created ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

The error message caught us off guard: ReferenceError: Storage is not defined

I utilize docsite for the creation of markdown documents and source code into HTML pages. Currently, I am looking to integrate a Valine plugin (a comment box feature) into my setup. My environment is node v10.9.0. Here's the location where I'm in ...

The JObject parser abruptly halts its execution without producing any results or indicating any errors

I have been attempting to retrieve and parse a JSON response from a webapi using the following code: var pemail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44302b2a3d37042329252d286a272b29">[email protected]</ ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Encountering a "Network Error" when attempting to use Passport Google OAuth in a React.js application

Implementing the Google Login feature using Passport has been challenging. Each time I send an axios request from my react client app, an error message pops up on the chrome console. On the Client Side - react (running on port 3000) : The Axios request i ...

Nextjs google places autocomplete not providing accurate suggestions

I'm attempting to utilize Google autocomplete to retrieve the names of mosques specifically in the United Kingdom. However, the data I am receiving is global and not limited to mosques. Here is my code: import axios from "axios"; export def ...

Should we pause JQUERY AJAX to prioritize usability, or only when absolutely necessary?

I am struggling with my LoadingStatus Function, which has two options: SHOW and HIDE. When a JQUERY POST is made, the Show option triggers to display, while the HIDE option occurs after the RESPONSE comes back. The problem I'm encountering is that s ...

The functionality of minified JS code is limited to being copied and pasted directly into the

Trying to explain the issue I'm facing may be a bit tricky, but here it goes: I've been working on an AngularJS app (not live yet) and we felt the need to add tooltips for specific metrics in our tables. After some research, we really liked the ...

How can I troubleshoot jQuery not functioning in iOS even though it works on Safari?

Trying to implement jQuery on a website using xCode simulator for testing, but experiencing issues. Works fine on Safari webkit though. Click here to view the site. I would appreciate finding out what's causing the problem, as well as advice on how t ...

Combine a JSON object and a JSON array by matching the value of the JSON object to the key of the JSON array

I am looking to create a JSON array in node by combining two JSON objects and arrays. `var template = { "key1": "value1", "key3": "value3", "key4": "value3", "key6": "Dummy Value1" }; var data = [ { "value1": "1", "value2": "2", ...

Ensure that the div automatically scrolls to the bottom when it is loaded, and also when new data is added - using angular

My goal is to replicate the functionality of the iPhone's "Messages" app on a web application using AngularJS or any other JavaScript framework. Each message will be contained in a div element within a larger container. When a new message is added, I ...

The transformation of a Raphael element does not occur as expected when it is passed to a function within a loop

My attempt to rotate an object by a variable number of degrees in order to mimic a dial was unsuccessful. Initially, I tried the following steps: window.onload = function() { var paper = new Raphael(document.getElementById('canvas_container ...

What is the best way to utilize ng-if to conceal a component in AngularJS when a button in a separate component is clicked?

I am facing a challenge with two child components within a parent component. My goal is to hide component1 when a button in component2 is clicked. Below is an illustration of the current code I am handling: Parent Component HTML: <div ng-app='ap ...