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.

1
  • I guess you just forgot the * Commented Oct 6, 2020 at 16:24

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.