Reputation: 3
<table id="table" border="1">
<tr>
<td>
<table border="1">
<tr>
<td>aaa</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table border="1">
<tr>
<td>bbb</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table border="1">
<tr>
<td>ccc</td>
</tr>
</table>
</td>
</tr>
</table>
<span id="append">append</span>
$('#append').click(function(){
$('table#table tr').append('<tr><td><table><tr><td>ddd</td></tr></table></tr>');
})
How can I use jQuery's append function on only the first element? When I use append here, it appends all subtables. I would only like to append the first subtable. I tried with the >
selector, but it is not working. How can I achieve this effect?
Upvotes: 0
Views: 1561
Reputation: 36784
You can use the first()
method:
$('#append').click(function(){
$('table#table tr').first().append('<tr><td><table><tr><td>ddd</td></tr></table></tr>');
})
Although that makes invalid HTML.. I think what you mean to append is:
<td><table><tr><td>ddd</td></tr></table></td>
Upvotes: 1
Reputation: 337560
If I've understood your requirements, the below should work. Note that I am appending to the first sub-table, as you cannot have a tr
as a direct child of a tr
(which is why you were ending up with another nested table
.
$('#append').click(function(){
$('#table table:first').append('<tr><td><table><tr><td>ddd</td></tr></table></tr>');
})
Upvotes: 0
Reputation: 6156
$("#table table tr:first").after('<tr><td><table><tr><td>ddd</td></tr></table></tr>');
Tested Live DEMO
Upvotes: 0
Reputation: 1308
Try this:
$('#append').click(function(){
$('table#table tr').first().append('<tr><td><table><tr><td>ddd</td></tr></table></tr>');
})
Upvotes: 1