Reputation: 1805
I have a table
<tbody>
<tr>
<td>101</td>
<td>37,17 m<sup>2</sup></td>
<td>1</td>
<td>3</td>
<td></td>
</tr>
<tr>
<td>102</td>
<td>30,53 m<sup>2</sup></td>
<td>1</td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>103</td>
<td>10,53 m<sup>2</sup></td>
<td>1</td>
<td>5</td>
<td></td>
</tr>
</tbody>
and i would like to get text from first and set it to id of parent to end like this
<tbody>
<tr id="101">
<td>101</td>
<td>37,17 m<sup>2</sup></td>
<td>1</td>
<td>3</td>
<td></td>
</tr>
<tr id="102">
<td>102</td>
<td>30,53 m<sup>2</sup></td>
<td>1</td>
<td>2</td>
<td></td>
</tr>
<tr id="103">
<td>103</td>
<td>10,53 m<sup>2</sup></td>
<td>1</td>
<td>5</td>
<td></td>
</tr>
</tbody>
i wrote something like this
var td = $('tobody td:first-child').text(); - returns 101102103
$('tobody tr').attr('id', td); - returns 101102103 for each tr
how to separate this ??
Upvotes: 1
Views: 896
Reputation: 74738
Traverse with .each()
in the <tr>
:
$('tbody tr').each(function(){
var txt = $.trim($('td:first',this).text());
$(this).attr('id', txt);
});
Upvotes: 0
Reputation: 148150
You can use each
to iterate through td
and assign the id
to the parent tr
$('td:first-child').each(function(){
$(this).closest('tr').attr('id', $.trim($(this).text()));
});
Upvotes: 1
Reputation: 9370
Try this:
$('tobody tr').each(function(){
$(this).attr('id', $(this).find("td:eq(0)").text().trim());
});
Or simply:
$('tbody tr').attr('id' , function(){
return $(this).find("td:eq(0)").text().trim();
});
Upvotes: 1
Reputation: 173642
Just iterate over all first <td>
elements, find the respective parent elements and set their id
attribute:
$('td:first-child').each(function() {
$(this).parent().attr('id', $(this).text());
});
If you have more tables or a bigger document, it makes sense to anchor the operation:
$('#table-id').find('td:first-child').each(function() {
var $this = $(this);
$this.parent().attr('id', $this.text());
});
Upvotes: 3
Reputation: 3407
$('tr').each(function() {
var $this = $(this),
theId = $this.find('td').first().text();
$this.attr('id', theId);
});
Please note that numeric ids are only valid in HTML5
Upvotes: 0