开发者

How to get the index of an <li> in a <ul> [duplicate]

开发者 https://www.devze.com 2023-03-04 16:15 出处:网络
This question already has answers here: Cl开发者_开发问答osed 11 years ago. Possible Duplicates:
This question already has answers here: Cl开发者_开发问答osed 11 years ago.

Possible Duplicates:

How to get index of <li> element

jQuery - get the index of a element with a certain class

I have:

<ul id="parent">
     <li id="li1">li1</li>
     <li id="li2">li2</li>
     <li id="li3">li3</li>
</ul>

There are some other <ul> and <li> tags elsewhere.

I want to get the index of li2 which is in the <ul> with id parent using jQuery


OLD simple answer: $('ul#parent li:eq(1)').index()

NEW $('#li2').index()


Use .index():

$('#li2').index();

IDs have to be unique so in case they are not in your HTML, you better fix this (e.g. by using classes).


var index = $("#li2").prevAll().length;  //assuming 0 based index
0

精彩评论

暂无评论...
验证码 换一张
取 消