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.

elano7
  • 1,584
  • 1
  • 18
  • 18
  • 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]`. – Tyler Roper Jun 16 '17 at 18:45

2 Answers2

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()
Terry
  • 63,248
  • 15
  • 96
  • 118
  • 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]`. – user229044 Jun 16 '17 at 18:46
  • @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. – Terry Jun 16 '17 at 18:52
  • Guys thank you a lot. I tried a lot, but I could never come alone to that conclusion. Thanks again! – elano7 Jun 16 '17 at 19:19
-1

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

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

john Smith
  • 17,409
  • 11
  • 76
  • 117