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

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

1
  • You want the first, second, OR third meaning any of the three? Or do you want all of them? And are you referring to three elements with the class .column, or three elements within a parent .column element? Commented May 13, 2012 at 3:13

4 Answers 4

35
$('#button').click(function() {
    alert($('.column').eq(0).val()); // first element
    alert($('.column').eq(1).val()); // second
    alert($('.column').eq(2).val()); // third
});
Sign up to request clarification or add additional context in comments.

1 Comment

Just as documentation: "Reduce the set of matched elements to the one at the specified index." jQuery.eq()
6

I like selector strings, so I usually do this:

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

1 Comment

I like them purely for style but it should be noted that the jQuery docs recommend .eq() over :eq() for performance on modern browsers: api.jquery.com/eq-selector
3

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 */
});

2 Comments

Slice could do it, but that function is really ideal for selecting a range if indices. Surely there is a function optimal for selecting a single index?
you mean like nth-child or eq()? You said you wanted the first 3, maybe I misunderstood but that seems to be the definition of a range of indices?
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.