Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to find out how to find the position that an item appears in a list. For example:

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

If I clicked on item 2, I would want to receive '2'. Is this possible?

like image 979
Ad Taylor Avatar asked Jan 23 '23 12:01

Ad Taylor


2 Answers

It's possible by using jquery's 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 it helps, Sinan.

like image 74
Sinan Avatar answered Jan 25 '23 00:01

Sinan


you could assign them IDs like

<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 IDs as Sinan says:

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

+1 because indexing starts from 0

like image 25
ant Avatar answered Jan 25 '23 01:01

ant