0

Hi I have this code. I need to get the 0 based index of the clicked element.

This is my code. I always get -1 as the index. Ideally clicking first link would print 0 and second would print 1. I am using jquery 1.3.2. JavaScript code is fine too.

What I am missing?

<script type="text/javascript"> function handleClick(id) { var par = document.getElementById('par'+id); alert('Index= ' + $('#clips').index(par)); } </script> <div id="clips" style="clear:both"> <div id="par30" class="alb rc32"> <div class="fl rc32 thm"> <a id="30" onclick="handleClick(30);">Link 1</a> </div> </div> <div id="par40" class="alb rc32"> <div class="fl rc32 thm"> <a id="40" onclick="handleClick(40);">Link 2</a> </div> </div> <div id="par50" class="alb rc32"> <div class="fl rc32 thm"> <a id="50" onclick="handleClick(50);">Link 3</a> </div> </div> </div> 

2 Answers 2

1

This works:

<script type="text/javascript"> function handleClick(id) { var $par = $('#par' + id); alert($par.index()); } 

 <div id="clips" style="clear:both"> <div id="par30" class="alb rc32"> <div class="fl rc32 thm"> <a href="javascript:void(0);" id="30" onclick="handleClick(30);">Link 1</a> </div> </div> <div id="par40" class="alb rc32"> <div class="fl rc32 thm"> <a href="javascript:void(0);" id="40" onclick="handleClick(40);">Link 2</a> </div> </div> <div id="par50" class="alb rc32"> <div class="fl rc32 thm"> <a href="javascript:void(0);" id="50" onclick="handleClick(50);">Link 3</a> </div> </div> </div> 
Sign up to request clarification or add additional context in comments.

2 Comments

You were too fast for me. :) This site seems competitive when it comes to answering things fast! That's good though.
lol - thanks - can you please mark this as the answer if it is correct.
0

You are using the index function wrong.

Try

<script type="text/javascript"> function handleClick(id) { var par = document.getElementById('par'+id); alert('Index= ' + $('#clips > div').index(par)); } </script> 

see http://api.jquery.com/index/

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

1 Comment

Sometimes its hard to be the first answer! I changed the selector used from '#clips' to '#clips > div' and then called index using that collection passing in the particular object you want the index of. Dr Rob's answer is also good. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.