javascript - Make .appendTo() apply to First Element? - Stack Overflow

admin2025-04-20  0

I have this code:

<ul id="hello">
    <li>.....</li>
    <li>.....</li>
    <li>.....</li>
    <li>.....</li>
    <li>.....</li>
    <li>.....</li>
</ul>

and this Script:

$("<label>The First item</label>").appendTo($('ul#hello li'));

How can I make it so that the .appendTo() function only applies to the first list item.

I've tried the :first-child selector but it doesn't seem to work.

Any help is appreciated.

I have this code:

<ul id="hello">
    <li>.....</li>
    <li>.....</li>
    <li>.....</li>
    <li>.....</li>
    <li>.....</li>
    <li>.....</li>
</ul>

and this Script:

$("<label>The First item</label>").appendTo($('ul#hello li'));

How can I make it so that the .appendTo() function only applies to the first list item.

I've tried the :first-child selector but it doesn't seem to work.

Any help is appreciated.

Share Improve this question asked Aug 24, 2011 at 14:23 shahmeer navidshahmeer navid 2351 gold badge5 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4
$("<label>The First item</label>").appendTo($('#hello li:first'));
$("<label>The First item</label>").appendTo($('#hello li').first());

Note: .first() should be a tad faster than :first. Also see: jQuery :first vs. .first()

$('#hello li:first').append('<label>The First item</label>');

or

$('#hello').find('li:first').append('<label>The First item</label>');

or

$('<label>The First item</label>').appendTo($('#hello').find('li:first'));

DEMO

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745106449a285318.html

最新回复(0)