Reputation: 59
I need to make changes to the DOM. I need to present the table content using paragaraphs or something like that. For that I need to get the data per each row of table. How can I do this?
HTML example:
<table style="width:300px">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Output should be something like this - Jill Smith 50
and Eve Jackson 94
I have written something like this, but it goes through all the <td>
tags in the web page. Not row wise.
$("table").each(function() {
$("tr").each(function(){
$("td").each(function(){
label = $('td').text();
});
alert(label);
});
Upvotes: 5
Views: 328
Reputation: 11
try,
FLAG = true;
text2 = "";
$("table tr").each(function(){
text1="";
$(this).find('td').each(function(){
text1 += $(this).text() + " ";
});
if(FLAG)
{
text2=text1+" "+"and"+" "
FLAG=false;
}
else
{
text2+=text1
}
});
alert(text2);
Upvotes: 1
Reputation: 1889
This is another solution. You can try!
$('table tr').each(function(i,e){
temp=[];
$(this).find('td').each(function(){
temp.push($(this).text());
});
resultBlock.append('"' + temp.join(' ') + '"');
if($(this).index()!=($('table tr').length-1)) resultBlock.append(' and ');
});
Upvotes: 0
Reputation: 4904
$('table tr').each(function () {
$('body').append($(this).text() + "<br/>");
alert($(this).text());
});
Iterate through each <tr>
.text()
property...
Upvotes: 0
Reputation: 2806
Give an ID to the table (for instance: mytable) and then do something like this:
$("#mytable").find("tr").each(function () {
var rowtext = "";
$(this).find("td").each(function () {
rowtext += $(this).text() + " ";
});
});
Why the ID? ID selectors are faster than element selectors and ensures the code runs only for the table you want, if you want the same code to run on multiple tables a class selector would be ideal.
Why not $("#mytable tr")? jquery reads the selectors right to left, this means that jquery would first find every "tr" element in the document and then filter by wether they have a parent with the id "mytable". Separating the selectors like this: $("#mytable").find("tr") ensures jquery only selects "tr" elements inside the element with "mytable" id.
Upvotes: 0
Reputation: 9637
try this
$("table tr").each(function (i, val) {
var t=$(this).map(function (i, val) {
return $(this).text();
}).get();
alert(t);
});
Upvotes: 0
Reputation: 67217
Try,
var groupedVales = [];
$('table tr').each(function(){
groupedVales[groupedVales.length] =
$(this).find('td').map(function(){ $(this).text(); }).get().join(' ');
});
Now the groupedvales
contains elements which will be grouped as per your expectations
Upvotes: 1