Nick Ginanto
Nick Ginanto

Reputation: 32130

jquery selector of class who have specific node immediatey after

consider the following html:

    <div class="a"> pick me 1</div>
    <div class="b"> stuff </div>
    <div class="a"> stuff </div>
    <div class="a"> stuff </div>
    <div class="a"> pick me 2</div>
    <div class="b"> stuff </div>
    <div class="a"> stuff </div>
    <div class="c"> stuff </div>
    <div class="b"> stuff </div>

I'd like to select only the divs which have .a and have .b immediately after, so I'll only get the pick me divs

Upvotes: 1

Views: 74

Answers (2)

Balint Bako
Balint Bako

Reputation: 2560

I stole the half from @BoltClock, nevertheless I think this is what you need:

$('div + .b + .a').prev().prev().css('color', 'red');

Especially if you want to make them red...

Upvotes: 1

BoltClock
BoltClock

Reputation: 723668

You need to start with the .b elements and step back to their preceding .a elements:

$('.b').prev('.a');

jsFiddle demo

Note that this does not include the .b elements, only the .a elements. A selector like .a + .b, on the other hand, would match the same structure but give you .b elements instead.

Upvotes: 9

Related Questions