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.
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.
var elem = $('li.selected');
$('ul li').index(elem);
This will return 1, as the elements index starts from 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.
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.