Is it possible to filter in css based on class name containing numbers?
Part of my html consists of code from external source which looks something like this:
<g>
<circle r="7" class="actor-0" cy="60" cx="20"></circle>
<circle r="7" class="actor-1" cy="60" cx="20"></circle>
</g>
...
<g>
...
<circle r="7" class="actor-2" cy="60" cx="20"></circle>
</g>
...
<g>
<circle r="7" class="actor-1" cy="60" cx="20"></circle>
<circle r="7" class="actor-2" cy="60" cx="20"></circle>
</g>
The numbers in actor names just keep increasing. I need to style them in some way and I would like to have them repeat colors for every n actors.
So actor-0
, actor-3
, actor-7
, … is lets say red
then actor-1
, actor-4
, actor-8
, … is lets say yellow and so on.
These circles are sprinkled also randomly in the HTML so they are not in single div therefore I can’t use the :nth-child()
option.
Maybe if there was a way to match actor and ending number of class name…
Is that doable in any way?
2
Answers
Directly targeting CSS class names with a pattern that includes incrementing numbers isn’t possible with plain CSS. However, you can use a combination of JavaScript and CSS to achieve the desired effect.
The idea is to use JavaScript to loop through the elements and apply a class based on the number in their class name. Then, you can define CSS rules for these applied classes.
Here’s an example approach:
1- JavaScript to Assign Classes Based on Pattern:
This script selects all elements whose class begins with actor-, extracts the number, and then adds a new class based on the modulo operation. For example, if you have 3 color groups, actor-0, actor-3, actor-6, etc., will all get color-group-0 class.
2- CSS to Style Based on New Classes:
This approach ensures that the coloring is dynamic and can handle an arbitrary number of actors. You just need to run the JavaScript after the page loads, and it will automatically categorize each actor into a color group.
This is a solution involving javascript that will grab all elements having a class starting with
actor-
and will apply a color cycling through an pre defined set: