Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make .appendTo() apply to First Element?

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.

like image 957
shahmeer navid Avatar asked Jul 14 '26 19:07

shahmeer navid


2 Answers

$("<label>The First item</label>").appendTo($('#hello li:first'));
like image 138
Alex Avatar answered Jul 17 '26 15:07

Alex


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

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

like image 24
Geert Avatar answered Jul 17 '26 14:07

Geert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!