-2

I have a few divs:

<div class="somediv">text</div>
<div class="somediv">text</div>
<div class="somediv">text</div>
<div class="somediv">text</div>

And when I click on for example the third div, I want to return the number 3.

I have tried something like this but it didn't work:

console.log($("this").index);
j08691
  • 204,283
  • 31
  • 260
  • 272
  • jQuery has an index function so you call it like `index()`. Post a [mcve] please including your click event handler – j08691 May 07 '21 at 14:29

2 Answers2

0

Remove the quotation marks - it should be console.log($(this).index());. Note: the index starts with 0.

Working example:

$('.somediv').on('click', function() {
    console.log($(this).index());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
    <div class="somediv">text</div>
    <div class="somediv">text</div>
    <div class="somediv">text</div>
    <div class="somediv">text</div>
</div>
biberman
  • 5,606
  • 4
  • 11
  • 35
  • Oh okay. I thought I had tried this and it had said "index is not a function", now I tried it again and it worked... thank you! – newnew123 May 07 '21 at 14:33
0

You can do something like:

var index = $(".somediv").index(this);

Hiro2k
  • 5,254
  • 4
  • 23
  • 28