0

I have a problem with the following code

var elements = $(".myClasses");
elements[1].animate({something},  1000);

If I use $(".myClasses").animate(...) it works, but why doesn't it work if I select just one element from the array?

I guess I maybe don't uderstand well the rules about objects or arrays.

1
  • Adding a [0] to a jQuery Object Array will return a DOM element instead of a jQuery element. Because .animate() is a jQuery method, it can only be used on jQuery objects. You're likely looking for $(".myClasses").eq(1) which is the jQuery equivalent to [1]. Commented Jun 16, 2017 at 18:45

2 Answers 2

1

That is because $(".myClasses") returns a jQuery object, and when you access it as an array it simply returns the DOM node and not a jQuery object. If you want to access them by index, simply use:

  • $(elements[1]), which converts the DOM node back into a jQuery object, so that you can apply jQuery methods to it, or
  • $(".myClasses").eq(1), which reduces a set of elements matched by the jQuery selector to a single element at the specified zero-based index. See documentation for .eq()
Sign up to request clarification or add additional context in comments.

3 Comments

This arrives at the right advice but for the wrong reasons. It's perfectly fine to use [] to fetch elements from a jQuery object, but they are returned as raw DOM nodes. There's nothing wrong with $('.myClasses')[1].
@meagar Thanks, I have updated my answer to reflect that. OP can of course convert elements[1] to a jquery object using $(elements[1]) and that will work :) not my typical modus operandi tho.
Guys thank you a lot. I tried a lot, but I could never come alone to that conclusion. Thanks again!
-1

if you want to use a jquery function you have to cast a jquery object you do it like

$(elements[1]).animate(...

1 Comment

This is a complete misuse of the term "cast". There's no casting involved here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.