Posted By

1man on 03/12/09


index jquery

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Find selected elements index

 / Published in: jQuery


Never used the index() method in jQuery but could be useful to know. Find a selected elements index when you click on it. Note the $('ul#mylist') inside the index method, gives the search some context of where to look for .selected, saves looking through all the DOM.

  1. //jQuery only
  2. var selected = $('ul#mylist li').index( $('.selected',$('ul#mylist')) );
  4. //Dirty Javascript / jQuery way
  5. var selected = 0;
  6. // Iterate through item in the list. If we find the selected item, return false to break out of the loop
  7. $(‘ul#mylist li’).each(function(index){
  8. if ($(this).hasClass(‘selected’)){
  9. selected = index;
  10. return false;
  12. }
  13. });

Report this snippet  

You need to login to post a comment.