Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the clicked li number

I have a standard list.

<ul>
  <li><a href="#">blah 1</a></li>
  <li><a href="#">blah 2</a></li>
  <li><a href="#">blah 3</a></li>
  <li><a href="#">blah 4</a></li>
</ul>

And my jQuery:

$('ul li a').live('click', function() {
  var parent = $(this).parent('li');
});

What I want to find out is the parent li's position in the list of the clicked link e.g. clicking on blah 3 would give me 2, blah 4 would give 3 etc.

like image 310
fire Avatar asked May 28 '10 08:05

fire


2 Answers

$('ul li a').live('click', function() {
    console.log($(this).parent('li').index());
});

Will give you what you want, but keep in mind these are 0 based indexes -- ie the first line item is index 0, the last line item is 3.

jQuery index() method documentation

like image 88
Erik Avatar answered Sep 24 '22 08:09

Erik


you can get the index of an element with jquery`s index

$('ul li a').live('click', function() 
{
    var index =  $(this).index();
});    
like image 20
Alex Pacurar Avatar answered Sep 22 '22 08:09

Alex Pacurar