Tsonev
Tsonev

Reputation: 435

jquery select each element who's previous element matches selector

I have the following question and I ve been struggling with it for quite a while. Im sure the solution is very simple but still I cant see it. In the following set of rows I want to select only the ones which contain class .replace or .empty or .delete or .insert and are preceded by rows which contain class .equal:

<tr>
    <th>sth</th>
    <td class="equal"> sth</td>
    <th>sth</th>
    <td class="equal"> sth</td>
</tr>
<tr>
    <th>sth</th>
    <td class="equal"></td>
    <th>sth</th>
    <td class="equal"></td>
</tr>
<tr>
    <th>want to be 1st selected row</th>
    <td class="replace"></td>
    <th></th>
    <td class="replace"> </td>
</tr>
<tr>
    <th>dont want this one but it selects it</th>
    <td class="replace"></td>
    <th>sth</th>
    <td class="replace"> sth</td>
</tr>
<tr>
    <th>sth</th>
    <td class="equal"></td>
    <th>sth</th>
    <td class="equal"></td>
</tr>
<tr>
    <th>want to be 2nd selected row</th>
    <td class="delete"></td>
    <th></th>
    <td class="delete"> </td>
</tr>
<tr>
    <th>sth</th>
    <td class="replace"></td>
    <th>sth</th>
    <td class="replace"> sth</td>
</tr>

So Ive come up with this as a jQuery( "prev + next" ) selector but it doesnt seem to work as it selects only the first row I want and then all others that have .replace in them and only after that jumps to the next .replace which was preceded by .equal :

$('tr:has(.equal) + tr:has(.replace),tr:has(.empty),tr:has(.delete),tr:has(.insert)')

Upvotes: 0

Views: 100

Answers (2)

Andrew
Andrew

Reputation: 5126

This is slightly more efficient, but wordier:

$("tr:has(.equal)").next("tr:has(.empty), tr:has(.insert), tr:has(.delete), tr:has(.replace)")

Fiddle, jsPerf

Upvotes: 2

Kevin B
Kevin B

Reputation: 95031

Select the previous elements, then use .next.

$(".equal").closest("tr").next().has(".replace,.empty,.delete,.insert");

It only selects table rows that have the specified classes and are preceded by a row that containing the equal class.

Upvotes: 1

Related Questions