Find the position of an element within a list

后端 未结 4 734
太阳男子
太阳男子 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 <a> for example:

    <ul id="test">
      <li><a href="#">Element 1</a></li>
      <hr /><hr />
      <li><a href="#">Element 2</a></li>
      <li><a href="#">Element 3</a></li>
    </ul>
    

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

    Also like in above example the list contains other elements like <hr /> 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.

    0 讨论(0)
  • 2021-01-12 00:42

    Use index():

    $("li").click(function() {
      var index = $(this).parent().children().index(this);
      alert("You clicked item " + index);
    });
    

    Indexes start at 0.

    0 讨论(0)
  • 2021-01-12 00:44

    A more efficient version of Cletus' answer, which doesn't require finding parents and children:

    $("li").on("click", function() {
      var index = $(this).index();
      alert(index);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
     <li>Element 1</li>
     <li>Element 2</li>
     <li>Element 3</li>
     <li>Element 4</li>
    </ul>

    0 讨论(0)
  • 2021-01-12 00:48

    Can also be done with plain JavaScript:

    let = _this = this,
          indx = Array.prototype.slice.call(_this.parentElement.childNodes).indexOf(_this);
    

    Or, if you trying to style your ordered html list with other than CSS like <hr>, as @Jan mentioned, use querySelectorAll('li') instead of childNodes.

    0 讨论(0)
提交回复
热议问题