简体   繁体   中英

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)')

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM