How to get the index of clicked element by class?

Viewed 123

I want to get the index of the clicked element in its list as well in its .blue class.

I figured out how to get the index in its list, but I can't figure out how to get the index in its .blue class. For example when I click the 5th button I want the to show 'index 4 - class index 3'.

Any ideas?

$('.showindex').click(function() {
  var index = $(this).closest("li").index();
  console.log("index " + index + " - class index " + "?");
});
.blue {
  color: blue;
}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

<ol id="ol1">
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
  <li><input type="button" value="Show index" class="showindex">showindex</li>
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
  <li><input type="button" value="Show index" class="showindex">showindex</li>
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
</ol>

1 Answers

To achieve this you can select all .blue elements and provide the current element as an argument to find its index within that collection.

Note that the last button will show its 'class index' as 2 because indexes are zero-based in JS. Try this:

let $blues = $('li:has(.showindex.blue)');

$('.showindex').click(function() {
  let $li = $(this).closest('li');
  let index = $li.index();
  let classIndex = $blues.index($li);
  
  console.log(`index ${index}, class index ${classIndex}`);
});
.blue {
  color: blue;
}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

<ol id="ol1">
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
  <li><input type="button" value="Show index" class="showindex">showindex</li>
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
  <li><input type="button" value="Show index" class="showindex">showindex</li>
  <li><input type="button" value="Show index" class="showindex blue">showindex blue/li>
</ol>

Related