prepare123
prepare123

Reputation: 165

How to find table tag td values using jQuery filter selector

<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

Answers (3)

Rayon
Rayon

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

Shubham Khatri
Shubham Khatri

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

guradio
guradio

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>

  1. First name the id to the table
  2. Use .nth-child() note:starts at 1

Upvotes: 1

Related Questions