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
  • 106,652
  • 57
  • 273
  • 297

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
  • 249,100
  • 51
  • 377
  • 410
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,950
  • 1
  • 18
  • 26