Get element index inside UL

Using jQuery, I would like to get the li index where the contained HREF anchor tag is "#All". (In this case, the correct result would be 3)

<div id="tabs"> <ul> <li><a href="#CPU"><span>CPU</span></a></li> <li><a href="#Pickup"><span>Pickup</span></a></li> <li><a href="#Breakfix"><span>Breakfix</span></a></li> <li><a href="#All"><span>All</span></a></li> </ul> </div> 

I tried:

 $("#tabs ul").index($("li a[href='#All']")) 

... no luck. What am I doing wrong?

+11
jquery
Jun 08 '09 at 16:42
source share
3 answers

This should do it:

 var index = $("#tabs ul li").index($("li:has(a[href='#All'])")); 
  • You have selected all <ul> instead of all <li> from which you want to get the index.
  • You should check if there is a <li> element: there is a link with what you want using the :has selector, otherwise the matching element will be << 25>, not <li> .

Tested above and it gives me the correct answer, 3, since the index is based on 0.

+27
Jun 08 '09 at 16:58
source share

I think because your first rule matches all UL elements when you want them to match all LI elements. Try:

 $("#tabs ul li").index($("li a[href='#All']")) 
+1
Jun 08 '09 at 16:55
source share

You want to get the index of an element inside another context, as part of a set of elements. See index () in the API documentation for more details, in particular examples.

 <script type="text/javascript"> $(document).ready(function(){ var which_index = $("#tabs ul li a").index($("a[href='#All']")); alert(which_index); }); </script> <body> <div id="tabs"> <ul> <li><a href="#CPU"><span>CPU</span></a></li> <li><a href="#Pickup"><span>Pickup</span></a></li> <li><a href="#Breakfix"><span>Breakfix</span></a></li> <li><a href="#All"><span>All</span></a></li> </ul> </div> </body> 
+1
Jun 08 '09 at 17:08
source share



All Articles