41

I have this code in jQuery:

children('table').children('tbody').children('tr').children('td')

Which gets all table cells for each row. My question is: how can I get the text value in each cell in each row?

Should I use .each() to loop trough all children('td')? How can I get the text value of each td?

Bojangles
  • 99,427
  • 50
  • 170
  • 208
Vlad
  • 2,739
  • 7
  • 49
  • 100
  • 1
    What do you want to do with this text value? How do you want it formatted? Please explain your situation with more detail. – Bojangles Nov 30 '11 at 12:06
  • I will use it as a plain text. Also some of the fields are needed as numbers/dates/time, for example i need time started. – Vlad Nov 30 '11 at 12:12

5 Answers5

74

First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each() to iterate through the collection:

ID Selector:

$('#mytable td').each(function() {
    var cellText = $(this).html();    
});

Class Selector:

$('.myTableClass td').each(function() {
    var cellText = $(this).html();    
});

Additional Information:

Take a look at jQuery's selector docs.

Thorsten
  • 5,634
  • 6
  • 35
  • 33
James Hill
  • 60,353
  • 20
  • 145
  • 161
16

You can use .map: http://jsfiddle.net/9ndcL/1/.

// array of text of each td

var texts = $("td").map(function() {
    return $(this).text();
});
pimvdb
  • 151,816
  • 78
  • 307
  • 352
6

I would give your tds a specific class, e.g. data-cell, and then use something like this:

$("td.data-cell").each(function () {
    // 'this' is now the raw td DOM element
    var txt = $(this).html();
});
jabclab
  • 14,786
  • 5
  • 54
  • 51
1
$(document).ready(function() {
  $('td').on('click', function() {
    var value = $this.text();
  });
});
barbsan
  • 3,418
  • 11
  • 21
  • 28
Love Kumar
  • 1,056
  • 9
  • 10
  • 1
    While your code may provide the answer to the question, please add context around it so others will have some idea what it does and why it is there. – Theo Jun 12 '19 at 11:25
0
$(".field-group_name").each(function() {
        console.log($(this).text());
    });
Rajan Mandanka
  • 2,003
  • 21
  • 13