David Elliott
David Elliott

Reputation: 21

Selecting specific data (td) from table

I need to select all the languages from the following table. The output should be Java, Ruby, Smalltalk, C++. What jQuery statement should I use? Thanks

<table id="languages" border="0" cellspacing="1">


<thead>
    <tr>
      <th>Language</th>
      <th>Type</th>
      <th>Invented</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Java</td>
      <td>Static</td>
      <td>1995</td>
    </tr>
    <tr>
      <td>Ruby</td>
      <td>Dynamic</td>
      <td>1993</td>
    </tr>
    <tr>
      <td>Smalltalk</td>
      <td>Dynamic</td>
      <td>1972</td>
    </tr>
    <tr>
      <td>C++</td>
      <td>Static</td>
      <td>1983</td>
    </tr>
  </tbody>
</table>

Upvotes: 0

Views: 67

Answers (3)

Ram
Ram

Reputation: 144689

You can use map method:

var lang = $('#languages td:first-child').map(function(){
       return this.innerHTML
}).get()

lang is an array of values(languages), in case that you want to store the values as a string you can use join method:

lang = lang.join(', ');

http://jsfiddle.net/hZqHc/

Upvotes: 2

MassivePenguin
MassivePenguin

Reputation: 3711

This will add each value to an array:

​var langs = [];
$('#languages tbody tr').each(function(){
    langs.push($(this).find('td:first').text()); 
});​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
console.log(langs);

You could just as easily append them to a string. ​ See http://jsfiddle.net/fXdkg/ for a working snippet.

Upvotes: 0

zgood
zgood

Reputation: 12571

var langs = '';    
$.each($('#languages tbody tr'), function(){
       langs += $(this).find('td:eq(0)').html() + ', ';
    });
langs = langs.substring(0, langs.length - 2);

Upvotes: 0

Related Questions