Norse
Norse

Reputation: 5757

JQuery get the nth element of array

$('#button').click(function() {
   alert($('.column').val());
});

How could I get the first, second, or third element in .column?

Upvotes: 20

Views: 27882

Answers (4)

Sampson
Sampson

Reputation: 268512

You could use the :lt (less-than) selector and tell it you want 0, 1, and 2 by indicating all .column elements below index 3:

$("#button").on("click", function(){
  $(".column:lt(3)").each(function(){
    alert( this.value );
  });
});

Demo: http://jsbin.com/icevih/edit#javascript,html

Upvotes: 2

Blender
Blender

Reputation: 298582

I like selector strings, so I usually do this:

$('.column:eq(3)') // Fourth .column element

Upvotes: 6

Jeff
Jeff

Reputation: 846

Use the Slice() function: http://api.jquery.com/slice/

See question: How to select a range of elements in jQuery

$('.column').slice(0, 2).each(function() {
    $(this).val();  /* my value */
});

Upvotes: 3

Elliot Bonneville
Elliot Bonneville

Reputation: 53371

$('#button').click(function() {
    alert($('.column').eq(0).val()); // first element
    alert($('.column').eq(1).val()); // second
    alert($('.column').eq(2).val()); // third
});

Upvotes: 35

Related Questions