Get the index number of elements relative to whole body not just relative to the nearest parent div

Viewed 44

I have found many questions and solutions on how doing this very basic thing in jQuery to get the index number.

$(".container p").click(function() {
  var index = $(this).index();
  alert(index);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <p>One</p>
  <p>Two</p>
  <p>Three</p>
</div>

Ok, that's great, but obviously this is relative to .container.

How could I get the index relative to the whole page, so that if I had another .container half way up the page the index would still be counted for the next ones.

Make sense?

1 Answers

To achieve this you can provide a selector to index() for it to find the current element within, like this:

$(".container p").click(function() {
  var index = $(this).index(".container p");
  console.log(index);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <p>One</p>
  <p>Two</p>
  <p>Three</p>
</div>
<div class="container">
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
</div>
<div class="container">
  <p>Seven</p>
  <p>Eight</p>
  <p>Nine</p>
</div>

Related