3

I need to know the position an item in HTML list.

<ul>
  <li>first</li>
  <li>second</li>
  <li>third</li>
</ul>

$('ul').on("click", function(event){
  var target = event.target;
})

So when I get the first li as the target of the event. How can I get 0 as result for the item postion. The only way I can think about is to iterate over all items and compare them with the event target, but I wonder if there is a better way to solve this.

Andreas Köberle
  • 98,250
  • 56
  • 262
  • 287

3 Answers3

3

You could use:

$('ul').on("click", function(event){
  var target = event.target,
      index = $(target).index();
  console.log(target, index);
})

JS Fiddle demo.

Reference:

David Thomas
  • 240,457
  • 50
  • 366
  • 401
2
var listItem = $(event.target);
alert('Index: ' + $('ul > li').index(listItem));
1
$('ul li').on("click", function(){
var index = $(this).index();
alert(index);
})

http://jsfiddle.net/6QZbT/

Sam
  • 2,892
  • 1
  • 17
  • 26