UPDATES VIA   RSS  |  Email Get updates via feedburner Get updates via twitter
Home / Coding / JavaScript & Ajax / JavaScript: How to get the i…

JavaScript: How to get the index (position within a group) of an object with jQuery?

Posted on 20. Jun, 2009 by 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.

Translate this post
                    
                    

Related posts:

  1. JavaScript: Send function as a parameter to another function (callbacks)
  2. JavaScript: GIFless animation. Animate images,logos with jQuery
  3. JavaScript: What if jQuery animation doesn’t fire/start?
  4. JavaScript: Where do I Find All Properties for All HTML Elements ?
  5. PHP Error: Call to a member function fetch_assoc() on a non-object in

  • Kemaloz

    It is veru useful. Thanks

    Tüm
    dünyadaki okey oyuncuları ile aynı platform içerisinde sohbet ederek canlı okey
    oynamaya hazır olun. http://www.okey-oyna.com sizi eğlenceye ve heyecana davet ediyor. İnternette görüntülü
    olarak okey oyna, gerçek kişilerle tanış, turnuva
    heyecanını yaşa. Dünyanın en büyük internet oyun portalı içerisine kayıt olun
    ve oynamaya hemen başlayın.