Reputation: 3840
I need to be able to dynamically determine what the index of a certain div inside another div is. For example:
<div id="parent">
<div id="div-0"></div>
<div id="div-5"></div>
<div id="div-1"></div>
<div id="div-2"></div>
<div id="div-3"></div>
<div id="div-4"></div>
</div>
For any of those I need to be able to know if a given div is the first, second etc...
EDIT: Ok obviously I haven't explained this well. I tried all of the below and all I get is 0 every time. I have edited the example above to reflect what is happening. So given the updated example what I need to be able to do is the following:
var index = $('#div-4').index();
Currently this is only returning 0 every time.
Upvotes: 2
Views: 3483
Reputation: 205979
$('#parent div').on('click',function(){
var elIndex = $(this).index();
$(this).text('my index is: '+ elIndex);
});
Good to know that in jQuery v lower that 1.3.3 .index()
will not work,
in that cases you can use .prevAll()
and length
:
var elIndex = $(this).prevAll().length;
This technique is specially useful if you have more than one class name as children, e.g. inside a DIV you have:
<div id="parent">
<div class="aa"></div>
<div class="bb"></div>
<div class="aa"></div>
<div class="bb"></div>
</div>
... and clicking on a '.aa' element you want to get it's 'index' than it would be something like:
$('#parent .aa').click(function(){
var elIndex = $(this).prevAll('.aa');
$(this).text('my index type of class name is: '+ elIndex);
});
Upvotes: 4
Reputation: 5985
You can use index as @amnotiam said (best way). And you can make manipulation using it or even one of thoses:
First, nth-child, closest or eq.
Upvotes: 0
Reputation: 13814
As am not i am notes in comment:
index()
Return Values
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
Upvotes: 0