3

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.

shahmeer navid
  • 235
  • 1
  • 5
  • 11

3 Answers3

4
$("<label>The First item</label>").appendTo($('#hello li:first'));
Alex
  • 7,320
  • 1
  • 18
  • 31
  • 2
    +1, also because passing the element name if you know the ID is useless. – pimvdb Aug 24 '11 at 14:33
  • 1
    @pimvdb: Not always. You could use the same ID on a different element on a different page. In that case `ul#hello` won't match `div#hello`. I admit, in practice this doesn't happen a lot. – Geert Aug 24 '11 at 14:46
  • @Geert: You shouldn't have 2 elements with the same ID, that defeats the whole purpose of IDs. – gen_Eric Aug 24 '11 at 14:52
  • @Rocket: I said: "same ID on a different element *on a different page*". That's perfectly valid and possible. – Geert Aug 24 '11 at 14:53
  • @Greet: Yes you did, sorry, I need more caffeine. – gen_Eric Aug 24 '11 at 15:01
4
$("<label>The First item</label>").appendTo($('#hello li').first());

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

Community
  • 1
  • 1
Geert
  • 1,804
  • 15
  • 15
1
$('#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

Amir Ismail
  • 3,865
  • 3
  • 20
  • 33