Muhammad Bilawal Muhammad Bilawal - 3 months ago 9
HTML Question

I have n list items. I need to get no of item which has class active

I am working on a slider which changes the active class on click of next and previous, I want the nth child each time which has class active.
e.g. in current scenario it should return 3

HTML

<div class="my-list">
<ul>
<li><a href="#"> list item</a></li>
<li><a href="#"> list item</a></li>
<li class="active"><a href="#"> list item</a></li>
<li><a href="#"> list item</a></li>
<li><a href="#"> list item</a></li>
<li><a href="#"> list item</a></li>
<li><a href="#"> list item</a></li>
</ul>
</div>


JavaScript

function getCurrentItem() {
var listItem = $(".my-list ul li");
var items = [];
for (i = 0; i < listItem.length; i++) {
items[i] = listItem;
if($(items[i]).hasClass("active")){
console.log("here: "+i);
}
}
}
getCurrentItem();

Answer

index() can be used to the the index of the element. Note that index() will return zero-based index of the element. So, in current example, it'll return 2.

return $('.my-list li.active').index();

If the index need to be start from 1, add one to the zero-based index.

return $('.my-list li.active').index() + 1;

console.log($('.my-list li.active').index() + 1);
.active {
  color: green;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-list">
    <ul>
        <li><a href="#"> list item 1 </a></li>
        <li><a href="#"> list item 2</a></li>
        <li class="active"><a href="#"> list item 3</a></li>
        <li><a href="#"> list item 4</a></li>
        <li><a href="#"> list item 5</a></li>
        <li><a href="#"> list item 6</a></li>
        <li><a href="#"> list item 7</a></li>
    </ul>
</div>