clarkcoorter
clarkcoorter

Reputation: 3

Append only for first element

<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?

LIVE DEMO

Upvotes: 0

Views: 1561

Answers (6)

George
George

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>

JSFiddle

Upvotes: 1

chead23
chead23

Reputation: 1879

Try $('table#table tr:first-child')

Upvotes: 0

Rory McCrossan
Rory McCrossan

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>');
})

Updated fiddle

Upvotes: 0

Vaibs_Cool
Vaibs_Cool

Reputation: 6156

$("#table table tr:first").after('<tr><td><table><tr><td>ddd</td></tr></table></tr>');

Tested Live DEMO

Upvotes: 0

Levi Kovacs
Levi Kovacs

Reputation: 1159

Take a look at the jQuery first-child selector

Upvotes: 0

Tdelang
Tdelang

Reputation: 1308

Try this:

$('#append').click(function(){
    $('table#table tr').first().append('<tr><td><table><tr><td>ddd</td></tr></table></tr>');
})

Upvotes: 1

Related Questions