1

How do I get the li element with class "selected" position inside it's container?

<ul>
  <li></li>
  <li class="selected"></li>
  <li></li>
</ul>

In this case it should return 2 as it's the second li inside it's container.

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

4 Answers4

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

This will return 1, as the elements index starts from 0.

Ankur
  • 791
  • 4
  • 15
0
$(".selected").index();

Check out the .index(...) jQuery function.

Note that the index function returns the node's position starting from zero, not from one, so the first element would be "in the zero index."

JCOC611
  • 19,111
  • 14
  • 69
  • 90
0

You may read this: How to get the element number/index between siblings

var selectedIndex = $("#selected").index() + 1;

var selectedIndex = $(".selected").index() + 1; (for you)

That was the accepted answer and it is good also for your question.

Also read Index() property.

Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
0

Try this

HTML

<ul>
    <li></li>
    <li class="selected"></li>
    <li></li>
</ul>​

JS

var selectedIndex=$("ul li.selected").index()+1; 
alert(selectedIndex); // outputs 2

Basically first index is 0 and second index is1, so +1 is being used according to your question two get the second index as 2 instead of 1.

DEMO.

The Alpha
  • 143,660
  • 29
  • 287
  • 307