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.
indexis always0because the<a>is the 1st child in its parent (the<ul>).Try getting the
<ul>‘s index instead.NOTE: Your HTML isn’t valid. The only valid children of
<ul>s are<li>s.