What is the most jquery-y way to get the numeric position of an element in a list? -


i want index of item in list similar this:

<ul>     <li>option 1</li>     <li class="selected">option 2</li>     <li>option 3</li> </ul>  // doesn't work var selected = #('ul#options li').index('.selected'); // selected should == 1 

i with

var selected = -1;  $('ul#options li').each(function(a, li){     if($(li).hasclass('selected')){         selected = $(li).parent().children().index(li);     } }); // selected == 1 

but seems there has cooler/more concise way accomplish this.

edit:

i came

$('ul#options li').index($('ul#options li.selected')); 

which better. turns out .index() needs object not selector string.

var selected = $('ul li.selected').index(); // 1 

jsfiddle.

the index 0 based, second item index of 1.

getting index in old versions of jquery convoluted, rather simple now. :)


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -