jQuery .eq() vs. .index()

Whenever a jQuery selector is called the results the selector returns are stored in an array. So for example a page with five <a> tags in the page will return an array containing those five anchor tags. Each <a> tag located in the array by order of appearance top to bottom in the DOM.

$('a'); //returns an array of all a tags in the DOM

One can target a specific <a> tag if the index of the tag is known. This is where the .eq() function comes into play. Simply pass the index of the result you would like to target in the parenthesis.

$('a').eq(2); // this will return the third &amp;amp;lt;a&amp;amp;gt; tag on the page
//(the index of the first item of an array is always 0)

As a comparison of the difference between .eq() and .index() this is where terminology becomes important. It is a bit confusing because you would think of .index() would do the same as example above. However this is not the functionality of .index(). The .index() function takes a jQuery selector as parameter. This function is run on something that is already a jquery/DOM Element. Based on the selector passed to .index() jQuery will determine what the index is of the DOM element it was run on. So consider the following example as this is easier to show then to explain.

Consider the same html page with 5 <a> tags on it. This time we add the class current to the last(5th) <a> tag:

$('a.current').index('a'); // returns 4 (for the index of the 5th &amp;amp;lt;a&amp;amp;gt; tag)

Subscribe to Stephen Tvedt

Get the latest posts delivered right to your inbox



Software, Photogaphy, Design, Music

Read More