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/
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.
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
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With