1

I have an element with CSS styles, and a randomly added number at the end of the class:

<div class="menu-523673 control-34689"></div>

I want to use wildcard css selector for the second element like this:

[class^="control-"] {
  color:red;
}

I looked at this post for inspiration.

It doesn't work I believe, because the element is in the middle. Is there any way I could achieve this result? I cannot use the wildcard selector on the first class name. It has to be the second one.

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
Pegaz
  • 367
  • 2
  • 12

2 Answers2

4

You can use this instead:

[class*=" control-"] {
  color: red;
}

The space at the start ensures that it doesn't match something like xyzcontrol-34689, only something like xyz control-34689.

[class*=" control-"] {
  color: red;
}
<div class="menu-523673 control-34689">Red text</div>

*= searches the whole attribute value, instead of just the start like ^= would.

As @DBS has noted in the comments, everything would break if control- is the first thing, so this is probably better:

[class*=" control-"], [class^="control-"] {
  color: red;
}

This matches either something that contains contains- anywhere in the attribute value, or contains- only at the start of the attribute value.

[class*=" control-"], [class^="control-"] {
  color: red;
}
<div class="control-34689">Red text</div>
<div class="menu-523673 control-34689">Also red text</div>
shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
2

Instead of ^=, you can use *= selector.

*= css selector selects elements whose css attribute value contains the substring.

[class*=" control-"] {
  color: red;
}
<div class="menu-523673 control-34689">Hello</div>
Derek Wang
  • 10,098
  • 4
  • 18
  • 39