wirey00
wirey00

Reputation: 33661

Why is .index() always returning 0

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/

Upvotes: 8

Views: 7325

Answers (3)

Alex W
Alex W

Reputation: 38193

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
});

Upvotes: 7

FishBasketGordo
FishBasketGordo

Reputation: 23142

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

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227240

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.

Upvotes: 12

Related Questions