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...
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?
5 Answers
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: .
// array of text of each td
var texts = $("td").map(function() {
return $(this).text();
});
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();
});
$(document).ready(function() {
$('td').on('click', function() {
var value = $this.text();
});
});
$(".field-group_name").each(function() {
console.log($(this).text());
});