Select Class That Does Not Begin with String

I want to select a child element that does not contain a class that begins with z-depth-:

<div class="well">
    <div class="well"></div>
</div>

So that if the inner .well also contained a class like z-depth-1 it would not be selected.

This isn't working because the inner .well is always selected:

.well .well:not([class^="z-depth-"])

Is that even possible?

3

2 Answers

You can't select a child element that does not contain a class that begins with z-depth- with CSS, you can only:

  1. Select all the child elements whose class attribute's values don't start from z-depth- substring:
.well .well:not([class^="z-depth-"]) {
    color: red;
}
<div class="well z-depth-1">Parent div
    <div class="z-depth-2 well">First child div</div>
    <div class="well z-depth-3">Second child div</div>
</div>
  1. Select all the child elements whose class attribute's values don't contain z-depth- substring:
.well .well:not([class*="z-depth-"]) {
    color: red;
}
<div class="well z-depth-1">Parent div
    <div class="z-depth-2 well">First child div</div>
    <div class="well z-depth-3">Second child div</div>
    <div class="well">Third child div</div>
</div>

You also could read more about all CSS Selectors on MDN.

6

You will need to combine ^= and *= to get the desired result.

.well:not([class^="z-depth-"]) { /*will ignore elements if the first class is z-depth-* */
  background-color: lightgreen;
}
.well:not([class*=" z-depth-"]) { /*will ignore elements if z-depth-* is second class or later */
  background-color: skyblue;
}
<div class="z-depth-1 well">z-depth-1 well</div>
<div class="well z-depth-1">well z-depth-1</div>

Here's a nice guide on how to use attributes selectors.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest