Select element by index (multiple elements of same class)

前端 未结 4 1230
半阙折子戏
半阙折子戏 2021-01-24 16:20

Is there a way to select a element by index with Javascript or jQuery? For instance:

相关标签:
4条回答
  • 2021-01-24 16:22

    http://api.jquery.com/eq/

    $("div.item").eq(0) will give you the first element.

    0 讨论(0)
  • 2021-01-24 16:27
    $('div.item:eq(4)');
    

    this code will select the 4th div with .item class

    0 讨论(0)
  • 2021-01-24 16:29

    $('div.item:eq(3)') or $("div.item").eq(3) or $("div.item").get(3)

    If you are talking about getting the "element", the third option returns the DOM element, versus the first two that return the jQuery object containing the DOM element.

    The first two are very similar. The difference is that the first one puts "eq" inside the query so you can only manipulate that single element. If you use the second one, you can do something like $("div.item").css('background','red').eq(3).css('background','blue') which cannot be done so easily using the other two methods.

    0 讨论(0)
  • 2021-01-24 16:49

    You could use the .eq() selector for this job:

    var element = $('div.item:eq(3)');
    
    0 讨论(0)
提交回复
热议问题