Reputation: 1028
I have the below HTML code:
<table id="tutorial" width="600" border="1">
<tr>
<td data-value="a">a</td>
<td>apple</td>
</tr>
<tr>
<td data-value="b">b</td>
<td>ball</td>
</tr>
<tr>
<td data-value="c">c</td>
<td>cat</td>
</tr>
and the below JavaScript:
$('#tutorial').find('tr').each (function(t) {
$(this).append('<td>',$('td', this).data('value'),'</td>')
});
jQuery adds the data-value after adding the first and the last parameter. So it is like this: <td></td>a
. The required behavior is <td>a</td>
Upvotes: 0
Views: 49
Reputation: 804
$(this).append('<td>' + $('td', this).data('value') + '</td>')
(basically just change the commas to pluses)
Upvotes: 2
Reputation: 36438
You want to append the value to your new td
, but your append
will add each item as a child of the tr
you're calling it on.
It's as though you said:
$(this).append('<td>'); // creates a new, complete TD
$(this).append($('td', this).data('value')); // stick some text after the TD
$(this).append('</td>'); // nothing to close, discarded
You want this:
$('<td>'). // create a TD
text($('td', this).data('value')). // set its text content
appendTo(this); // append to the row
Upvotes: 2
Reputation: 24638
Here is how you need to write the jQuery to get the desired effect:
$('#tutorial').find('tr').each (function() {
$(this).append( $('<td/>',{text:$('td',this).data('value')}) )
});
Upvotes: 1