Reputation: 231
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
Reputation: 19561
There are a few ways, but $('#someTableId').find('tr').eq(2)
would work.
th
with td
s inside them, that should still be a tr
element with th
elements inside it, see the fixes in the example belowHere'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
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
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