3

How do I know the how manieth an element is? (using Javascript or jQuery) Suppose I have one UL with multiple LI within, how do I know wheter the LI clicked is the 4th or the 6th?

$('li').click(function(){
    nth = $(this).nth();
    alert(nth);
});
Jan Werkhoven
  • 2,656
  • 1
  • 22
  • 31

5 Answers5

6

You can use jQuery's .index for this.

​$("li").click(function() {
    var nth = $("ul li").index($(this));
    alert(nth);
});​

Live example

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • The advantage of this answer above the answers using $(this).index() is that it also works correctly if some of the children of the ul element are not li elements. – Confusion Jun 19 '12 at 19:53
  • @Confusion - If the ul had direct children that weren't li elements, would they be valid elements? https://developer.mozilla.org/en/HTML/Element/ul I guess that doesn't change the fact that some browsers would consider them in the index anyway. – Kevin B Jun 19 '12 at 20:00
  • @KevinB - I thought you were allowed to nest lists directly, but it seems that has been deprecated, as discussed in e.g. http://stackoverflow.com/questions/5899337/proper-way-to-make-html-nested-list – Confusion Jun 19 '12 at 20:46
2
$('li').click(function(){
    alert($(this).index());
});
Dale
  • 10,384
  • 21
  • 34
1

you could try a nth = $(this).prevAll().count() + 1

Rodolfo
  • 4,155
  • 23
  • 38
1

You could use the index method:

var nth = $(this).index()+1;
Kevin B
  • 94,570
  • 16
  • 163
  • 180
0

I do something like

$('li').each(function (i) {
  $(this).data("pos", i);
}).click(function() {
  var nth = $(this).data("pos");
  alert(nth);
});

Invariably, I end up needing the position for other things, so I save it off.

mpdonadio
  • 2,891
  • 3
  • 35
  • 54