CSS Attribute Selector Wildcard Capture Tool

Suppose I have the following HTML structure:

<div class="tocolor-red">    tocolor </div>
<div class="tocolor-blue">   tocolor </div>
<div class="tocolor-green">  tocolor </div>
<div class="tocolor-yellow"> tocolor </div>

Instead of duplicating CSS code for each color variation like in the example below...

.tocolor-red{
  background: red;
}
.tocolor-red::before {
  content: "red";
}

... is there a way to create a CSS rule that dynamically assigns the color based on the class name? While exploring attribute selectors and wildcard options, I haven't found a solution that captures the dynamic text from the class.

If regular expressions were applicable in CSS, the rule might resemble something similar to this hypothetical example:

.tocolor-([\w+]) {
   background: $1;
}
.tocolor-([\w+]:before {
   content: $1;
}

Answer №1

Although CSS lacks the capability to support regular expression captures, you can still target all elements with a class that starts with the string tocolor-. However, CSS does not have the ability to extract and apply the captured value to a rule.

As an alternative solution, albeit somewhat delayed, consider using JavaScript:

// Selecting all elements containing the string 'tocolor-':
var elements = document.querySelectorAll('[class*="tocolor-"]'),

// Declaring variables for later use:
    classes, colorString;

// Iterating over the collection of elements,
// utilizing Function.prototype.call() in order to employ
// Array.prototype.forEach() on the collection:
Array.prototype.forEach.call(elements, function (elem) {
    // 'elem' represents each individual node in the collection.

    // Generating an array of classes from the element:
    classes = Array.prototype.slice.call(elem.classList, 0);

    // Creating a new array using Array.prototype.map():
    colorString = classes.map(function (c) {
        // 'c' denotes the specific class being iterated over.

        // Check if the current class ('c') begins with 'tocolor-',
        // then return that class after removing 'tocolor-' string:
        if (c.indexOf('tocolor-') === 0) {
            return c.replace('tocolor-','');
        }
    });

    // Applying the extracted color as the style of the element ('elem'):
    elem.style.color = colorString;
});

var elements = document.querySelectorAll('[class*="tocolor-"]'),
  classes, colorString;
Array.prototype.forEach.call(elements, function(elem) {
  classes = Array.prototype.slice.call(elem.classList, 0);
  colorString = classes.map(function(c) {
    if (c.indexOf('tocolor-') === 0) {
      return c.replace('tocolor-', '');
    }
  });
  elem.style.color = colorString;
});
<div class="tocolor-red">tocolor</div>
<div class="tocolor-blue">tocolor</div>
<div class="tocolor-green">tocolor</div>
<div class="tocolor-yellow">tocolor</div>

Answer №2

Your unique element:

span[class*='.custom-'] {
    color: blue;
}

If you want to incorporate variables, consider checking out LESS:

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

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

Deselect all child elements when the parent checkbox is not selected

Creating a page that features multiple checkboxes, some nested and others not. When a particular checkbox is selected, additional options will be displayed underneath it for selection; if unchecked, the child boxes will be hidden. Currently, this functiona ...

Having issues sorting the ranking table numerically in a Javascript/jQuery/JSON/localStorage game

I have successfully created a leaderboard for my game, but I am struggling to automatically sort the scores from high to low. I believe that placing the objects into an array and then sorting them may be the solution, however, I am unsure of how to do th ...

Utilizing CSS3 webkit-transitions with multiple properties on a div element along with multiple webkit-transition-delays

Is there a way to make a div slide 200px to the right and then reduce its scale by half separately? I want it to slide first and then scale, but currently both transformations happen simultaneously. I tried using webkit-transition-delay to set different ...

What exactly does the question mark represent in the code structure as indicated in VSCode?

When looking at the image, you can see that in the description of done(), VSCode indicates the type of parameters using a colon error: any or sometimes with a question mark and colon user?: any. So, what exactly is the distinction between these two ways o ...

The textbox fails to update when the condition in the IF statement is met

In the following code, I have an input box with the ID volumetric_weight that gets updated on keyup. However, the second textbox with the ID volumetric_price does not update as expected, even though I believe I wrote it correctly. I am wondering if there ...

What is the process for setting a cookie in Next.js from a different backend server?

I have encountered an issue with my Node.js API built using Express.js. The cookie I set works perfectly fine on Postman, but for some reason, it is not functioning properly in Next.js. I set the cookie when a user logs in, but it is not appearing in the b ...

Create a regex pattern that can accurately extract email addresses from a comma-del

Currently, I have a regular expression that validates a single email address. How can I modify this regex to accept a list of email addresses separated by commas? ^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A- ...

The tooltip in chart.js stubbornly holds onto past data even after it's been

Utilizing chart.js, I have implemented a feature where a tooltip displays when a user hovers over the chart successfully. However, I encountered an issue. I added an option for users to un-check data-points, which works correctly. But now, the tooltip fun ...

Verify and deselect boxes

Can someone help me with checking and unchecking checkboxes? I'm facing a lot of issues with it. You can find my code snippet here: http://jsfiddle.net/N5Swt/: <input type="checkbox" id="checkbox1" /> <span> Check me! </span> // ...

Angular4 - Div with ngIf doesn't respond to click event

I'm attempting to add a click event to a specific div. Within this div, there is another div that is dynamically generated based on a Boolean condition that I receive as input. Unfortunately, in this case, the click event is only functioning when clic ...

Is there a way to use HTML and JS to draw custom lines connecting elements?

Sorry if this question has been asked before. Is there a way to create straight lines connecting HTML elements with just HTML and JavaScript, without relying on SVG or Canvas? If so, what would be the most effective approach? ...

I have managed to update the Immutable and Primitive Data-Types in JS. Now, the question arises - are these truly Primitives or are the concepts in

In JavaScript, there are 4 primitive data types that store values directly: String, Number, Boolean, and Symbol. I am excluding undefined and null from this list as they are special data types with unique characteristics. One key feature of primitives is ...

Adjust the dimensions of the bootstrap dropdown to match the dimensions of its textbox

The second textbox features a bootstrap dropdown with extensive content that is overflowing and extending to other textboxes below it. I am looking for a way to resize the dropdown to fit the size of its corresponding textbox. UPDATE: I want the dropdown ...

Issue with IE7 causing rollover navigation blocks to disappear when hovering over content

While conducting browser testing on the website The website's top navigation menu includes rollover effects for building services, exterior services, and commercial categories. The CSS-triggered navigation works seamlessly in all browsers except for ...

Integrating a Google map into an Ionic Side-Menu application

I am trying to incorporate a Google map into my Ionic app. I followed the code provided in this https://developers.google.com/maps/documentation/javascript/adding-a-google-map and it worked fine in Angular, but not in my side-menu Ionic project. The specif ...

The creation of a MozillaBrowserBot object has encountered an error

Attempting to access the MozillaBrowserBot object in Mozilla JS has been unsuccessful for me. The code I utilized is shown below: function externalApplication(){ var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Com ...

Error encountered when generating bower.json due to absence of version number

After generating the bower.json file, I noticed that the version number was not included in the information collected. The current content is as follows: { "Name": "conFusion", "Authors": [ "Aurora" ], ... } Although the version n ...

How can I resolve the issue of encountering the "Modal dialog present: If you navigate away from this page, any unsaved changes will be lost" message while using Internet Explorer with

Here's the code snippet I'm working with. While it successfully removes the alert box, it throws an error in the console: Exception in thread "main" org.openqa.selenium.UnhandledAlertException: Modal dialog present: If you leave this page, any c ...

Styling a playbook using CSS Grid management techniques

Exciting to create a playbook layout style, here's how it goes: Name: Text starting here - unique style #1 text that moves to a new line with a different look - unique style #2 more text continuing on another new line ...