Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of an element excluding an element with a specific class?

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.

like image 944
Rebecca O'Riordan Avatar asked Mar 05 '23 22:03

Rebecca O'Riordan


1 Answers

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>
like image 166
Mohammad Avatar answered Apr 30 '23 06:04

Mohammad