I have a table like this
<table>
<tr><td id="space_bet1" height="10"></td></tr>
<tr><td id="unscr1">Today</td></tr>
<tr><td id="space_bet2" height="10"></td></tr>
<tr><td id="unscr2">Tomorrow</td></tr>
<tr><td id="space_bet3" height="10"></td></tr>
<tr><td id="unscr3">Yesterday</td></tr>
<tr><td id="space_bet4" height="10"></td></tr>
<tr><td id="unscr4">next week</td></tr>
<tr><td id="space_bet5" height="10"></td></tr>
<tr><td id="unscr5">next month</td></tr>
<tr><td id="space_bet6" height="10"></td></tr>
</table>
I want find the td before space_bet3, I tried prev() method but it don't work anyway
alert($("#space_bet3").prev().prev().attr("id")) // undefined error
alert($("#space_bet3").prev("#space_bet2").attr("id")) // undefined error
what is my wrong to do that? how can find id before of space_bet3, Thank you
As there is no sibling(<td>
) before the element #space_bet3
, prev()
on it will return empty set.
<tr>
ancestor<tr>
sibling<td>
id
attribute value.code:
$('#space_bet3')
.closest('tr') // Get first ancestor `<tr>` element
.prev() // Get previous element
.children('td') // Get direct descendant `<td>` element
.attr('id'); // Get `id` of the element
var id = $('#space_bet3')
.closest('tr') // Get first ancestor `<tr>` element
.prev() // Get previous element
.children('td') // Get direct descendant `<td>` element
.attr('id'); // Get `id` of the element
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table>
<tr>
<td id="space_bet1" height="10"></td>
</tr>
<tr>
<td id="unscr1">Today</td>
</tr>
<tr>
<td id="space_bet2" height="10"></td>
</tr>
<tr>
<td id="unscr2">Tomorrow</td>
</tr>
<tr>
<td id="space_bet3" height="10"></td>
</tr>
<tr>
<td id="unscr3">Yesterday</td>
</tr>
<tr>
<td id="space_bet4" height="10"></td>
</tr>
<tr>
<td id="unscr4">next week</td>
</tr>
<tr>
<td id="space_bet5" height="10"></td>
</tr>
<tr>
<td id="unscr5">next month</td>
</tr>
<tr>
<td id="space_bet6" height="10"></td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With