admin管理员组

文章数量:1287591

I have this table, how Can I get the first precessor that has the .cep class and get this element with Jquery??

This is my table:

<table>
    <tr class="cep"></tr>
    <tr class="ptype"></tr>
    <tr class="item"></tr>
    <tr class="cep"></tr> (I want to get this element)
    <tr class="ptype"></tr>
    <tr class="item"></tr>
    <tr class="item-here"></tr> (I'me here)
    <tr class="item"></tr>
</table>

Is there a way to do this:

$('tr.item-here').prevUntilFindThefirstMatchOf('tr.cep'); Get this element

Help please

I have this table, how Can I get the first precessor that has the .cep class and get this element with Jquery??

This is my table:

<table>
    <tr class="cep"></tr>
    <tr class="ptype"></tr>
    <tr class="item"></tr>
    <tr class="cep"></tr> (I want to get this element)
    <tr class="ptype"></tr>
    <tr class="item"></tr>
    <tr class="item-here"></tr> (I'me here)
    <tr class="item"></tr>
</table>

Is there a way to do this:

$('tr.item-here').prevUntilFindThefirstMatchOf('tr.cep'); Get this element

Help please

Share Improve this question asked Jul 30, 2015 at 20:57 juanpscottojuanpscotto 1,0501 gold badge14 silver badges32 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

I suggest using prevAll in bination with first. prevAll will filter all previous siblings by your selector and first just grabs the first one it es across.

$('tr.item-here').prevAll('tr.cep').first();

var meh = $('tr.item-here').prevAll('tr.cep').first();

console.log($(meh).text());
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr class="cep"><td>This should not print in console</td></tr>
    <tr class="ptype"></tr>
    <tr class="item"></tr>
    <tr class="cep"><td>This should print in console</td></tr>
    <tr class="ptype"></tr>
    <tr class="item"></tr>
    <tr class="item-here"></tr>
    <tr class="item"></tr>
</table>

Use prevUntil()

console.log($('tr.item-here').prevUntil('tr.cep').last().prev());
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
    <tr class="cep">cep</tr>
    <tr class="ptype">ptype</tr>
    <tr class="item">item</tr>
    <tr class="cep">cep</tr> 
    <tr class="ptype">ptype</tr>
    <tr class="item">item</tr>
    <tr class="item-here">item-here</tr>
    <tr class="item">item</tr>
</table>

本文标签: javascriptGet the first previous element that matches a condition with JqueryStack Overflow