jQuery find an element by its index

后端 未结 7 1808
灰色年华
灰色年华 2020-12-21 16:18

If I have a selection

item 1
item 2
item 3
相关标签:
7条回答
  • 2020-12-21 16:41

    Either of these:

    • .index - This is the getter. Get the index of a given element, and apply logic, based on it.
    • .eq, :eq or .slice- These can be used to get an element from a given jQuery collection
    • :nth-child - Select an element which is the nth child (!!) element, respective to the parent.

    In your case, eq or :nth-child are suitable. Eg:

    var item1 = $('#container > :nth-child(1)');  // parent > child (=first child)
    var item2 = $('#container').children().eq(1); // Zero-based indexes
    
    0 讨论(0)
  • 2020-12-21 16:43
    $('#container').children().eq(1);
    
    0 讨论(0)
  • 2020-12-21 16:47

    You can use :eq selector like below,

       $('#container div:eq(2)') //will return you div with item 2
    
    0 讨论(0)
  • 2020-12-21 16:49

    Use eq() method.

    $("#container > div").eq(1)
    

    You can even use :eq(1) pseudo selector.

    $("#container > div:eq(1)")
    

    .eq(index) reduces the set of matched elements to the one at the specified index.

    :eq(index) selects the element at index n within the matched set.

    0 讨论(0)
  • 2020-12-21 16:49

    Try:

    $("#container div").eq(1) // zero-based, so will select 'item 2'
    
    0 讨论(0)
  • 2020-12-21 16:49
    $('#container').children().eq(2);
    
    0 讨论(0)
提交回复
热议问题