Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Index Of Element Within UL

Tags:

jquery

Using jQuery, I'd like to be able to get the index of the li where the contained anchor tag's HREF equals "#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 have tried:

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

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

like image 676
Steve Horn Avatar asked Jun 08 '09 16:06

Steve Horn


3 Answers

This should do it:

var index = $("#tabs ul li").index($("li:has(a[href='#All'])"));
  • You were selecting all <ul> instead of all <li>s you wanted to get the index out of.
  • You have to check if the <li> element :has a link with what you want by using the :has selector, otherwise the matched element will be the <a> itself instead of the <li>.

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

like image 182
Paolo Bergantino Avatar answered Oct 02 '22 19:10

Paolo Bergantino


I think it's because your first rule is matching all UL elements, when you want it to match all LI elements. Try:

$("#tabs ul li").index($("li a[href='#All']"))
like image 45
robertc Avatar answered Oct 02 '22 21:10

robertc


You want to get an element's index inside another context, as part of a set of elements. See index() in the API documentation for more information, particularly the 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>
like image 22
artlung Avatar answered Oct 02 '22 20:10

artlung