Find the position of the element in the whole html document

Viewed 30

I don't mean the position, x and y! I want to find the position of the element based on its class. For example, in the code of the html document, we have 4 test classes. When one of them is clicked, I want to find the position that of elements among other friends who shared the same class.

<div>
    <div>
        <p class="test">one</p>
    </div>
    <p class="test">two</p>
    <span href="" class="test">three</span>
</div>
<div class="test">four</div>
1 Answers

Use $.index:

const $els = $('.test');
$els.click(function() {
  const index = $els.index(this);
  console.log('The clicked element is the number', index);
});
Related