Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return jQuery object (instead of DOM) from jQuery array using index

I have a jQuery array of <span>s and I'd like to get just one of them as a jQuery object so that I can string additional methods on it. Something like $mySpans[2] (which returns a string), or $mySpans.get(2), (which returns the DOM element directly).

I know that this will work:

$($mySpans[2]).someJQueryMethod( ... );

...but it seems a little redundant. What is the right way to do this?

like image 356
brentonstrine Avatar asked May 22 '13 22:05

brentonstrine


2 Answers

Like this:

$myspans.eq(2).method();
like image 80
elclanrs Avatar answered Nov 02 '22 23:11

elclanrs


jsFiddle Demo

You are going to want to use eq. Note that it will return the jQuery object wrapped element at that index, so if you only have one match you should use 0 (which follows that 2 will return the third of the set).

var $thirdMatch = $mySpans.eq(2);//== jQuery object with third match
var htmlElement = $thirdMatch[0];//== actual dom element
var matchedHtml = $thirdMatch.html();// call some jQuery API method

It is common practice when storing jQuery objects to use a $variableName for readability purposes.

like image 39
Travis J Avatar answered Nov 02 '22 21:11

Travis J