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
  • 96,145
  • 48
  • 166
  • 203
Vlad
  • 2,671
  • 7
  • 44
  • 96
  • 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

72

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,554
  • 6
  • 33
  • 33
James Hill
  • 58,309
  • 18
  • 142
  • 160
15

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

// array of text of each td

var texts = $("td").map(function() {
    return $(this).text();
});
pimvdb
  • 146,912
  • 75
  • 297
  • 349
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,220
  • 5
  • 49
  • 49
1
$(document).ready(function() {
  $('td').on('click', function() {
    var value = $this.text();
  });
});
barbsan
  • 3,328
  • 11
  • 20
  • 28
Love Kumar
  • 930
  • 8
  • 9
  • 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
  • 1,905
  • 19
  • 12