Find the position of an element within a list

后端 未结 4 733
太阳男子
太阳男子 2021-01-12 00:08

I\'m looking to find the position (i.e. the order) of a clicked element within a list using jQuery.

I have:

  • Element 1
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 00:36

    Previous answer works fine. 2 additions:
    When your list contains listitems of for example:

    
    

    then you have to use var index = $(this).parent().parent().children().index(this);

    Also like in above example the list contains other elements like


    than you can use a filter in var index = $(this).parent().parent().children("li").index(this); to give you index 2 for "element 3" instead of index 4.

提交回复
热议问题