Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery get the nth element of array

Tags:

arrays

jquery

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

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

like image 521
Norse Avatar asked May 13 '12 02:05

Norse


People also ask

How to get nth element from array in jQuery?

To access element with nth index from an HTML page, use the jQuery eq() method. It is used to access the index of an element in jQuery. The eq() method refers the position of the element.

How to get the nth child of an element in jQuery?

jQuery :nth-child() Selector The :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.

What is EQ jQuery?

jQuery eq() Method The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).

Which of the following CSS selectors will select the second div in jQuery?

myclass:eq(1)" ) selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification. Prior to jQuery 1.8, the :eq(index) selector did not accept a negative value for index (though the . eq(index) method did).


3 Answers

$('#button').click(function() {
    alert($('.column').eq(0).val()); // first element
    alert($('.column').eq(1).val()); // second
    alert($('.column').eq(2).val()); // third
});
like image 108
Elliot Bonneville Avatar answered Nov 13 '22 04:11

Elliot Bonneville


I like selector strings, so I usually do this:

$('.column:eq(3)') // Fourth .column element
like image 35
Blender Avatar answered Nov 13 '22 04:11

Blender


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 */
});
like image 31
Jeff Avatar answered Nov 13 '22 05:11

Jeff