Why .index () always returns 0

I am confused why. index () returns 0 in this code. Should it return an index of where it is found in the jquery object array?

<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/

+6
source share
3 answers

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

Try to get the <ul> index.

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

NOTE. Your HTML is not valid. The only valid <ul> children are <li> s.

+9
source

There are no siblings in your anchor elements, so they are all indexes 0. They are all nested in their own <ul> , which, if I am not mistaken, is invalid markup without including <li> around the anchor.

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

+3
source

Another reason .index() can return 0 is if you use it like this:

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

The right way:

 $('matched elements').click(function(){ console.log($('matched elements').index($(this))); // will be the index within set of matched elements }); 
+3
source

Source: https://habr.com/ru/post/921982/


All Articles