简体   繁体   中英

Getting text from td cells with jQuery

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 ?

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 .

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

// array of text of each td

var texts = $("td").map(function() {
    return $(this).text();
});

I would give your tds a specific class, eg 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();
});
$(document).ready(function() {
  $('td').on('click', function() {
    var value = $this.text();
  });
});
$(".field-group_name").each(function() {
        console.log($(this).text());
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM