Reputation: 165
<table>
<tr>
<td>Calories </td>
<td>TargetValue1</td>
</tr>
<tr>
<td>Protein</td>
<td>TargetValue2</td>
</tr>
<tr>
<td>Protein</td>
<td>TargetValue3</td>
</tr>
How can I select all second td values?
I tried
$.each($("#nutritab tbody tr td:eq(1)"),function(i , item){
alert($(item).text());
});
but that only returns the first values.
Upvotes: 3
Views: 144
Reputation: 36609
Use
nth-child
selector instead of:eq(index)
The :nth-child(n)
selector matches every element that is the nth child()
(Index starts from 1
)
The :eq(index)
selector selects the element at index n within the matched set.(Zero-based index
)
$.each($("#nutritab tr td:nth-child(2)"), function(i, item) {
alert($(item).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='nutritab'>
<tr>
<td>Calories</td>
<td>TargetValue1</td>
</tr>
<tr>
<td>Protein</td>
<td>TargetValue2</td>
</tr>
<tr>
<td>Protein</td>
<td>TargetValue3</td>
</tr>
</table>
Upvotes: 3
Reputation: 281874
You can use the :nth-child(n)
selector, it matches every element that is the nth child() of selector
:
$('.tb').each(function(index, tr) {
alert($(this).find('td:nth-child(2)').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="tb">
<tr>
<td>Calories </td>
<td>TargetValue1</td>
</tr>
<tr>
<td>Protein</td>
<td>TargetValue2</td>
</tr>
<tr>
<td>Protein</td>
<td>TargetValue3</td>
</tr>
</table>
Upvotes: 1
Reputation: 15555
$.each($("#nutritab tbody tr"), function(i, item) {
alert($(this).find('td:nth-child(2)').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='nutritab'>
<tr>
<td>Calories</td>
<td>TargetValue1</td>
</tr>
<tr>
<td>Protein</td>
<td>TargetValue2</td>
</tr>
<tr>
<td>Protein</td>
<td>TargetValue3</td>
</tr>
nth-child()
note:starts at 1Upvotes: 1