8

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?

2 Answers 2

10

Like this:

$myspans.eq(2).method();
Sign up to request clarification or add additional context in comments.

5 Comments

Why was this method named eq? That seems like an awful name. I know index also exists, but that should arguably have been indexOf or something
eq or "equals". index does something completely different. You can still use slice just like a regular array if that makes more sense.
How does $myspans "equals" 2 make any sense? I understand that index/indexOf is traditionally used to search a collection and return an item's index, but even if index wasn't used, I just think a better name could be found.
@voithos Indeed, it's a poorly named method. There is no equivalent in the CSS spec so the jQuery authors were left to their own naming decisions, and clearly made a bad call. There are plenty of other examples of naming failures - for example $.grep() and $().filter() do the same thing but you have to use one or the other depending on whether you have some tags already selected.
I think it makes sense. It's modeled after the :gt and :lt selectors, so :eq makes complete sense to me. I read it as select where index equals 2
5

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.