I have a list which may or may not have a non-selectable list-item added to it dynamically. It looks like this (with the non-selectable list-item included):
<ul class="list js-list ">
<li class="listLabel">
<span>Make Selection:</span>
</li>
<li class="js-sppmg__li">
<span class="listItem js-listItem" data-filter-id="All">All</span>
</li>
<li class="js-sppmg__li">
<span class="listItem js-listItem" data-filter-id="One">One</span>
</li>
<li class="js-sppmg__li">
<span class="listItem js-listItem" data-filter-id="Two">Two</span>
</li>
<li class="js-sppmg__li">
<span class="listItem js-listItem" data-filter-id="Three">Three</span>
</li>
</ul>
When I click on the third list item which is data-filter-id="Two"
, I want the index:
parentIndex = $(this).parent().index();
to exclude the first, non-inclusive element which is listLabel
. Is it possible to not include it in the index count? I've tried using .not()
and class selectors etc but it returns either the same value as always (3 instead of 2) or -1.
You need to select all li
except .listLabel
using :not()
selector
$(".listItem").click(function(){
var index = $(this).closest("ul").find("li:not(.listLabel)").index($(this).parent());
console.log(index);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="list js-list ">
<li class="listLabel">
<span>Make Selection:</span>
</li>
<li class="js-sppmg__li">
<span class="listItem js-listItem" data-filter-id="All">All</span>
</li>
<li class="js-sppmg__li">
<span class="listItem js-listItem" data-filter-id="One">One</span>
</li>
<li class="js-sppmg__li">
<span class="listItem js-listItem" data-filter-id="Two">Two</span>
</li>
<li class="js-sppmg__li">
<span class="listItem js-listItem" data-filter-id="Three">Three</span>
</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With