Mr Bitmap
Mr Bitmap

Reputation: 231

how can I get an item in the specific table row using jQuery

I have a table and I want to get the image source in the third row using jquery.

<tr>
    <th>First Name</th>
    <th>Last Name</th>
     <th>Age</th>
     <th>Avatar</th>
  </tr>      
 <tr>
    <td>Peter</td>
    <td>Jason</td>
    <td>29</td>
     <td><img src="json.gif"/></td>
  </tr>
  <tr>
    <td>Victoria</td>
    <td>Cooper</td>
    <td>38</td>
     <td><img src="cooper.gif"/></td>
  </tr>

Upvotes: 1

Views: 1189

Answers (3)

Wesley Smith
Wesley Smith

Reputation: 19561

There are a few ways, but $('#someTableId').find('tr').eq(2) would work.

find()

eq()

NOTE

  • in your headder row, your HTML is malformed, you have the row as th with tds inside them, that should still be a tr element with th elements inside it, see the fixes in the example below
  • The below adds an ID to the table in order to target only that table's rows, adjust as needed

Here's a simple example

$('#someTableId').find('tr').eq(2).addClass('test');
.test td {
background-color:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="someTableId"> 
<tr>
    <th>First Name</th>
    <th>Last Name</th>
     <th>Age</th>
     <th>Avatar</th>
  </tr>     
 <tr>
    <td>Peter</td>
    <td>Jason</td>
    <td>29</td>
     <td><img src="json.gif"/></td>
  </tr>
  <tr>
    <td>Victoria</td>
    <td>Cooper</td>
    <td>38</td>
     <td><img src="cooper.gif"/></td>
  </tr>
</table>

Upvotes: 2

Ram Segev
Ram Segev

Reputation: 2573

you can use css pseudo selector nth-child()

The :nth-child() CSS pseudo-class matches elements based on their position in a group of siblings

You can read more here :nth-child

.

console.log($('#tableID tr:nth-child(3) img').attr('src'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableID">
 <tr>
  <th>
      <td>First Name</td>
      <td>Last Name</td>
      <td>Age</td>
      <td>Avatar</td>
  </th> 
 </tr>
 <tr>
    <td>Peter</td>
    <td>Jason</td>
    <td>29</td>
     <td><img src="json.gif"/></td>
  </tr>
  <tr>
    <td>Victoria</td>
    <td>Cooper</td>
    <td>38</td>
     <td><img src="cooper.gif"/></td>
  </tr>
</table>

Upvotes: 1

thienDX
thienDX

Reputation: 294

You can get the n-th element by :eq()

https://api.jquery.com/eq-selector/

For your case :

$("td:eq(2) > img").attr('src');

Upvotes: 2

Related Questions