st4ck0v3rfl0w
st4ck0v3rfl0w

Reputation: 6755

Get ID of first LI of UL with jQuery

<ul id="someList">
<li id="listItem1">List 1</li>
<li id="listItem2">List 2</li>
</ul>

Maybe I need to brush up on my selectors, but how would you grab the first ID of ul#someList?

Also if I'm prepending LI's to ul#someList, will I need to grab the first LI's ID in a different way?

Upvotes: 4

Views: 45413

Answers (4)

Selim Reza
Selim Reza

Reputation: 1084

This may be another solution:

$('#someList li:nth-child(1)').attr("id");

Upvotes: 1

SoftwareGeek
SoftwareGeek

Reputation: 15762

Try, ****.slice( start, [ end ] )****`

<ul>
  <li id='l1'>list item 1</li>
  <li id='l2'>list item 2</li>
  <li id='l3'>list item 3</li>
  <li id='l4'>list item 4</li>
  <li id='l5'>list item 5</li>
</ul>

$('li').slice(2).attr('id');

Upvotes: 1

Corey Sunwold
Corey Sunwold

Reputation: 10254

Your best bet is to use the first selector.

var id = $("ul#someList li:first").attr("id");

or

var id = $("ul#someList li:first").get(0).id;

Upvotes: 3

user11977
user11977

Reputation: 1793

$('ul#someList li:first') is what you're looking for.

Upvotes: 28

Related Questions