22

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
  • 665,005
  • 155
  • 1,345
  • 1,328
Tarang
  • 74,439
  • 37
  • 212
  • 270

4 Answers4

31

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,563
  • 10
  • 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
5
.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
  • 18,870
  • 12
  • 73
  • 98
1

Try:

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

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

Kai Sellgren
  • 23,990
  • 8
  • 69
  • 83
0

With CSS3 pseudo classes:

.classa:not(:last-child):not(.classb) {
  // some rules...
}
ldiqual
  • 15,027
  • 6
  • 48
  • 89