3

So why is this? Very confused...Thanks!

$('#navigation ul li a:first').index($('#navigation ul li a')) >> returns 0 expect 0

$('#navigation ul li a:last').index($('#navigation ul li a')) >> returns -1 expect 19

$('#navigation ul li a').eq(2).index($('#navigation ul li a')) >> returns -1 expect 2

UPDATE: here are some html, it's my pagination code:

 <div id="navigation"> <ul> <li><a class="current" href="#1-1">1</a></li> <li><a class="" href="#1-2">2</a></li> <li><a class="" href="#1-3">3</a></li> <li><a class="" href="#1-4">4</a></li> <li><a class="" href="#1-5">5</a></li> <li><a class="" href="#1-6">6</a></li> <li><a class="" href="#1-7">7</a></li> <li><a class="" href="#1-8">8</a></li> <li><a class="" href="#1-9">9</a></li> <li><a class="" href="#1-10">10</a></li> <li><a class="" href="#1-11">11</a></li> <li><a class="" href="#1-12">12</a></li> <li><a class="" href="#1-13">13</a></li> <li><a class="" href="#1-14">14</a></li> <li><a class="" href="#1-15">15</a></li> <li><a class="" href="#1-16">16</a></li> <li><a class="" href="#1-17">17</a></li> <li><a class="" href="#1-18">18</a></li> <li><a class="" href="#1-19">19</a></li> <li><a class="" href="#1-20">20</a></li> </ul> </div> 
5
  • You need to give a little more than that... some code perhaps... and some html... Commented Sep 3, 2011 at 21:07
  • Could you post that in jsfiddle.net ? Commented Sep 3, 2011 at 21:09
  • 3
    You're calling index on the wrong array: it returns the index of the element in the array you're calling index on. Commented Sep 3, 2011 at 21:09
  • thanks. what's the right way then? i also did: $('#navigation ul li a:last').parent().index() >>returns -1 expect 20 Commented Sep 3, 2011 at 21:13
  • The way you had it would have been correct if you just passed a selector string instead of a jQuery object, like this: $('#navigation ul li a:last').index('#navigation ul li a') Commented Sep 3, 2011 at 21:28

2 Answers 2

8

You need to reverse your selectors:

alert($('#navigation ul li a').index($('#navigation ul li a:first'))); // 0 alert($('#navigation ul li a').index($('#navigation ul li a:last'))); // 19 alert($('#navigation ul li a').index($('#navigation ul li a').eq(2))); // 2 

SEE DEMO

Sign up to request clarification or add additional context in comments.

Comments

3

-1 means that element wasn't found by index()

try indexing the list items instead of anchors as they are on the same level

var listItems = $('#navigation ul li'); $('#navigation ul li:first').index(listItems); $('#navigation ul li:last').index(listItems); $('#navigation ul li').eq(2).index(listItems); 

1 Comment

'$('#navigation ul li:last').index() returns -1 expected 19' :( also did $all = $('navigation ul li'); $('navigation ul li:last').index($all) >>returns -1 expected 19

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.