How to find the index of a row in a table using jquery

前端 未结 5 691
执笔经年
执笔经年 2020-12-01 18:28

I\'m trying to find the index of a row in a table. I\'m trying to use the following code, but I seem to get an index of -1.

$(document).ready(function()
{
           


        
相关标签:
5条回答
  • 2020-12-01 18:42

    Try:

    var index = $("table tr").index(this);
    

    The documentation for index() says:

    Searches every matched element for the object and returns the index of the element, if found, starting with zero. If a jQuery object is passed, only the first element is checked.

    You need to call the index() on a collection of <tr> elements, not the parent <table>.

    0 讨论(0)
  • 2020-12-01 18:45

    I've just found an interesting trick, which basically consists on counting the previous siblings:

    var tr = $(some_selector);
    var rowIndex = tr.prevAll().length;
    

    This way you will get 0 if this is the first tr, 3 if this is the 4th tr, etc.

    Just for the sake of it, another option using index(), which saves you from having to know how to select the containing table:

    var rowIndex = tr.parent().children().index(tr);
    
    0 讨论(0)
  • 2020-12-01 18:48

    Get the td object and its parent index is tr index

    $(this).parent().index()
    
    0 讨论(0)
  • Based on Robs answer to find index in specific table, this worked for me.

    var index = $('tr', $(this).closest("table")).index(this);
    
    0 讨论(0)
  • 2020-12-01 18:51

    Have you tried:

    $("tr").index(this)
    

    The documentation shows just passing this and that the preceding selection should be where the node is found. If you need to find it in a specific table (and there are multiple), you may need to provide some context:

    // haven't tested this
    $("tr", $(this).closest("table")).index(this) 
    
    0 讨论(0)
提交回复
热议问题