Shijin Shijin - 7 months ago 28
Javascript Question

Get index of li have a class and do not have another class

I have the below code to find the index of li have the class

active
and do not have
hidden
class. In order to find the value we don't want to count
hidden
class.



var index = $('li').not('.hidden').find('.active').index();
alert(index)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="hidden">.....</li>
<li>....</li>
<li class="hidden">....</li>
<li class="active">....</li>
<li>....</li>
<li class="hidden">....</li>
<li>....</li>
</ul>





Here I got result -1.but my expected result is 1.is it possible to find this?

Answer

You can use .filter(), it searches in same level i.e. a subset of the matching elements where as .find() looks in descendant elements

var index = $('li').not('.hidden').filter('.active').index();

OR, It can be improved as

var index = $('li.active:not(.hidden)').index();

If you need to exclude .hidden, then you need to remove them from unordered list then .index() can be used.

var index = $('ul').clone().find('li.hidden').remove().end().find('li.active').index();

var index = $('ul').clone().find('.hidden').remove().end().find('li.active').index();
alert(index)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="hidden">.....</li>
  <li>....</li>
  <li class="hidden">....</li>
  <li class="active">....</li>
  <li>....</li>
  <li class="hidden">....</li>
  <li>....</li>
</ul>

Comments