Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find previous td element using jquery

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

like image 959
MojtabaSh Avatar asked Sep 26 '22 23:09

MojtabaSh


1 Answers

As there is no sibling(<td>) before the element #space_bet3, prev() on it will return empty set.

  1. Get the <tr> ancestor
  2. Get previous <tr> sibling
  3. Get the children <td>
  4. Get the 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>
like image 114
Tushar Avatar answered Sep 30 '22 07:09

Tushar