24

I've tried all sorts of things but I think i'm getting too complicated and even managed to get chrome to hang with my selector. I'm sure theres a simple way to do this

Select classa but only when theres no classb and ignore the last instance of it

<div class="container">
    <div class="classa classb"></div> <!-- Dont Select -->
    <div class="classa"></div>  <!-- Select -->
    <div class="classa"></div>  <!-- Dont select last instance -->
</div>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Tarang
  • 75,157
  • 39
  • 215
  • 276

4 Answers4

32

I believe you can do this with CSS3 using the :not() selected (example here)

div.classa:not(.classb):not(:last-child) {}

However, as you know, not many browser supports this, so Javascript might be an easier way...

LeeR
  • 1,609
  • 11
  • 29
  • Also, you won't be able to exclude the last `.classa` if it's not the last child. See http://stackoverflow.com/questions/10230416/is-it-possible-using-current-browsers-to-use-pseudo-classes-to-detect-first-and/10230466#10230466 – BoltClock May 27 '12 at 10:12
  • Yes this is a problem ive been getting testing – Tarang May 27 '12 at 10:13
6
.classa:not(.classb):not(:last-child) {
    /* rules */
}

Tested on Firefox 12, Chrome 19, Safari 5 and Opera 10. Unfortunately it doesn't work on (...guess who?) IE.

Simone
  • 20,302
  • 14
  • 79
  • 103
1

Try:

.classa:not(.classb):first-child {
    background: red;
}

This won't work in IE 7 or 8 though.

Kai Sellgren
  • 27,954
  • 10
  • 75
  • 87
0

With CSS3 pseudo classes:

.classa:not(:last-child):not(.classb) {
  // some rules...
}
ldiqual
  • 15,015
  • 6
  • 52
  • 90