How to return the order in which an item appears in a list in jQuery?

I am trying to figure out how to find the position at which an item is displayed in a list. For instance:

<ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> 

If I clicked on element 2, I would like to get "2". Is it possible?

+4
source share
5 answers

Perhaps using a jquery index .

EDIT:

 <ul id="my_list"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> 

and in js,

 var $my_list = $('#my_list'); $my_list.find('li').click(function(){ var index = $('ul#my_list li').index(this); alert(index); }); 

this should do what you need.

hope this helps, Sinan.

+7
source

you can assign them an ID, for example

 <ul> <li id="1">item 1</li> <li id="2">item 2</li> <li id="3">item 3</li> </ul> 

then:

 $("li").live('click', function(){ alert($(this).attr("id")); } 

or without identifiers, as Sinan says:

 $("li").live('click', function(){ alert($("li").index(this) + 1); } 

+1 because indexing starts at 0

+2
source
 $("ul#your_ul li").click(function () { // this is the dom element clicked var index = $("ul#your_ul li").index(this) + 1; }); 

You need to tell ul that you want to do this on id, otherwise it will return the index li in terms of all li inside ul s, which is not what you want.

+2
source

Pseudo code

 $('ul > li').each(function(el) { el.ClickEvent(function() { alert(el.preceding-siblings.count() + 1); }); }); 

Something like this anyway, sorry, did not manage to get a syntax spot on

-1
source
 okie i have edited my answer do this $(function() { var _item=1; $('ul li').each(function(){ var _elm=$(this).attr('_elm',_item); }).bind('click',_handle); _item++; }); function _myClick(e) { var _yourValue=$(e.target).attr('_elm'); //this is the value u were looking for } 
-1
source

Source: https://habr.com/ru/post/1302478/


All Articles