Big_Chair
Big_Chair

Reputation: 3239

Accessing selected values like an Array in JavaScript

I know you can access the first element like this $(".myClass:first")

But is there a way to do it with an index like in JavaScript .getElementsbyClassname("MyClass").[0]?

Something like:
$(".MyClass:[5]")

Upvotes: 0

Views: 62

Answers (4)

user2571870
user2571870

Reputation:

I personally use this.

$(".myClass").eq(index);

Also you can get the element index among the matched elements here. For example:

$(".myClass").click(function(){
    $(this).index();
});

Upvotes: 5

Jason P
Jason P

Reputation: 27012

These will give you a jQuery object containing the element at that index:

$(".MyClass:eq(5)")
$(".MyClass:eq(" + idx + ")")
$(".MyClass").eq(idx);

This will give you the element at the index:

$(".MyClass")[idx]
$(".MyClass").get(idx)

Upvotes: 1

Paulo Lima
Paulo Lima

Reputation: 1238

yes there just use the selector "eq"

$(".MyClass:eq(5)")

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

Upvotes: 3

$(".MyClass:nth-child(5)")

:nth-child()

Upvotes: 1

Related Questions