JavaScript: How to get the index (position within a group) of an object with jQuery?
Posted on 20. Jun, 2009 by Dragos in Coding, JavaScript & Ajax
I’ve spent some time today figuring out how to obtain that index and finally I’ve just puzzled it out.
Let’s say we have a group of objects all containing the class=”house”. Now if we are referencing to the first element within the group and we’d like to find out it’s index (well it’s obvious in this case), we’d use this piece of code:
var indexOfFirstElement=$('.house').index($('.house:first')); //indexOfFirstElement=0;
So, the code works as follows: we’re searching within all elements of a group all grouped by the class=”house” ( $(‘.house’) ). Now we are looking for the index if an element within this group, in our case it’s the first element of the group ( $(‘.house’).index($(‘.house:first’)) ).
Here’s another example to help you better understand how index() works:
$('.house').each(function(i){
if(i==3) alert($('.house').index(this)); //alerts 3, supposing there are 3 or more elements with class="house"
});
So basically, if you need to find out the index of an element within a group, you should first specify the group and then pass the object you need to find the index of as a parameter to the index() function.
Related posts:
- JavaScript: Send function as a parameter to another function (callbacks)
- JavaScript: GIFless animation. Animate images,logos with jQuery
- JavaScript: What if jQuery animation doesn’t fire/start?
- JavaScript: Where do I Find All Properties for All HTML Elements ?
- PHP Error: Call to a member function fetch_assoc() on a non-object in
-
Kemaloz










































