Reputation: 461
for convenience I wanted to be able to reference my JQuery selectors from an array rather than individually. I was led to believe that the following logic would enable me to do so:
var reference = $('.class');
reference[0].<function>;
instead of:
$reference1 = $('#id1');
$reference2 = $('#id2');
$reference3 = $('#id3');
$reference1.<function>
all of my elements have the appropriate class and are being populated into the array(?) but for some reason I can't then call JQuery functions from the array in the same way I can with a single selector. Is there something I'm missing or a reason I can't do this?
Upvotes: 0
Views: 98
Reputation: 411
reference[0]
refers to an Element instead of a jQuery object.
If you want to refer to the first object matching a selector, use .first():
/* This returns a jQuery object. */
reference.first();
If you want the object at index n, use ':eq(n)' in your selector, or the eq() method. These are zero-indexed:
/* This returns a jQuery object. */
$('.class:eq(n)');
/* This returns a jQuery object. */
reference.eq(n);
You could also "re-wrap" an element, but this is not idiomatic:
/* This returns an Element. */
reference[n];
/* This returns a jQuery object. */
$(reference[n]);
Similarly, you could use get. But the methods above are preferable:
/* This returns an Element. */
reference.get(n);
/* This returns a jQuery object. */
$(reference.get(n));
What wrapping means:
This is our page:
<!DOCTYPE html>
<html>
<head>
<title>Hey</title>
</head>
<body>
<p>You</p>
<p>!!!</p>
</body>
</html>
This creates a jQuery object named $p
, selecting the two <p>
Elements:
/* This returns a jQuery object. */
var $p = $('p');
This object has all those useful jQuery methods we love:
$p.css('color', 'purple'); /* this colors all paragraphs purple */
Like I said, we can select the second (or first) paragraph with .eq()
:
/* This returns a jQuery object. */
$p.eq(1); /* this selects the second paragraph (because indices start at 0) */
Or we could do it like you were trying to do:
/* This returns an Element. */
$p[1];
But this gives us a plain old Element, and not a jQuery object. However, if we apply the jQuery function, we get back a jQuery object, and we can use all our beloved jQuery methods:
$($p[1]).text('???');
Applying $
again to an Element is what I called re-wrapping.
Upvotes: 1
Reputation: 133403
Your first example code doesn't works as reference[0]
will fetch underlying DOM element and those doesn't have jQuery methods, thus you must be getting error.
.eq(index)
can be used
Reduce the set of matched elements to the one at the specified index.
Change your code as
var reference = $('.class');
reference.eq(0).fn()
Upvotes: 2