3

I am trying to apply an effect to the first element in an array but I recieve this error:

$(...)[0].hide is not a function

Here is my code:

var contain = $('.commentFormContainer');
(contain.length >= 2 ) ? contain[0].hide();
Shivam
  • 2,208
  • 3
  • 24
  • 39

1 Answers1

8

You need to use eq() to get the jQuery object. You can not use indexer as it will give you DOM object and you can not call hide on it.

contain.eq(0).hide(); 

Or you can use :eq in selector.

$('.commentFormContainer:eq(0)').hide();

Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $('.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, Reference.

Adil
  • 146,340
  • 25
  • 209
  • 204
  • `Or you can use :eq in selector, it would be more efficient` - how is that true? You've clearly read the docs, knowing that it's a jQuery extension, not a regular CSS selector. That means there's no improvement in using the `":eq()"` selector instead of `.eq()`, because jQuery has to get all elements, then filter manually in both situations. I would think using the selector is less efficient because jQuery has to parse the string and do more, while `.eq()` is straightforward and easier for jQuery. – Ian Jul 19 '13 at 15:03