Find selected elements index

/ Published in: jQuery
Save to your folder(s)

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.

Copy this code and paste it in your HTML
  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


RSS Icon Subscribe to comments

You need to login to post a comment.