0

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]")

4 Answers 4

5

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

"get the element index among the matched elements"? $(".myClass").index(this).
3

yes there just use the selector "eq"

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

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

1 Comment

I always like to point out this note from the documentation when mentioning :eq: "Because :eq() is a jQuery extension and not part of the CSS specification, queries using :eq() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").eq(index) instead."
1
$(".MyClass:nth-child(5)")

:nth-child()

2 Comments

One important difference between nth-child and the eq selector is the nth-child is 1-based whereas eq is 0-based.
nth-child also does not work with all browsers that a company may be trying to support, e.g., corporate customers who don't upgrade IE versions quickly.
1

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)

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.