Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .index() always returning 0

Tags:

jquery

I'm confused as to why .index() is returning 0 in this code. Shouldn't it return the index of where it's found in the array of jquery objects?

<div id="nav">
       <ul><a href="#">Link 1</a></ul>
       <ul><a href="#">Link 2</a></ul>
       <ul><a href="#">Link 3</a></ul>
       <ul><a href="#">Link 4</a></ul>    
</div>
<div class="parent">
    <div class="a">
        <p>this is a</p>
    </div>   
    <div class="b">
        <p>this is b</p>
    </div>
    <div class="c">
        <p>this is c</p>
    </div>
    <div class="d">
        <p>this is d</p>
    </div>
</div>

jQuery code

 $('#nav a').click(function() {
    console.log($(this).index());
    var $div = $('.parent > div').eq($(this).index());
    $div.show();
    $('.parent > div').not($div).hide();
});​

I have to use $(this).index('#nav a') to get the correct index.

http://jsfiddle.net/HpCWW/2/

like image 966
wirey00 Avatar asked Aug 02 '12 18:08

wirey00


3 Answers

index is always 0 because the <a> is the 1st child in its parent (the <ul>).

Try getting the <ul>'s index instead.

$(this).parent().index()

NOTE: Your HTML isn't valid. The only valid children of <ul>s are <li>s.

like image 84
Rocket Hazmat Avatar answered Oct 23 '22 18:10

Rocket Hazmat


Another reason that .index() could return 0 is if you are using it like so:

$('matched elements').click(function(){
    console.log($(this).index()); // will be 0 in some cases
});

Correct way:

$('matched elements').click(function(){
    console.log($('matched elements').index($(this))); // will be the index within set of matched elements
});
like image 30
Alex W Avatar answered Oct 23 '22 19:10

Alex W


Your anchor elements don't have any siblings, so they're all index 0. They're all nested in their own <ul>, which if I'm not mistaken, is invalid markup without include <li> around the anchors.

I would change your HTML to this:

<div id="nav">
    <ul>
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
        <li><a href="#">Link 3</a></li>
        <li><a href="#">Link 4</a></li>
    </ul>
</div>
<div class="parent">
    <div class="a">
        <p>this is a</p>
    </div>   
    <div class="b">
        <p>this is b</p>
    </div>
    <div class="c">
        <p>this is c</p>
    </div>
    <div class="d">
        <p>this is d</p>
    </div>
</div>

And you JS to this:

$('.parent  div').hide();

$('#nav a').click(function() {
    // Notice, I'm going up to the parent <li> and then calling index().
    var $div = $('.parent > div').eq($(this).parent().index());
    $div.show();
    $('.parent > div').not($div).hide();
});​

Working example

like image 3
FishBasketGordo Avatar answered Oct 23 '22 18:10

FishBasketGordo