0

I want to know what position a div has in an argument: by this I mean, that if I have several divs witht the same name, like so:

<div class="woot"></div>
<div class="woot"></div>
<div class="woot"></div>
<div class="woot"></div>
<div class="woot"></div>

I would like to detect onclick what position the div click takes: 1st, 2nd....

Keavon
  • 6,837
  • 9
  • 51
  • 79
Fyxerz
  • 169
  • 1
  • 14

2 Answers2

2

Use the index() function, it will return a zero-based index of the clicked element within the selection:

$('.woot').click(function(){
    var clickedIndex = $('.woot').index($(this));
})

See it here: http://jsfiddle.net/xtbu13gh/

Shomz
  • 37,421
  • 4
  • 57
  • 85
1
<div class="parent">
   <div class="woot"></div>
   <div class="woot"></div>
   <div class="woot"></div>
   <div class="woot"></div>
   <div class="woot"></div>
</div>
<script type="text/javascript">

$(document).ready(function(){

   var woots = $(".parent").find(".woot");

   $(woots).each(function(index){
       $(this).attr("data-position", index);
   });

   $(".parent").on("click", ".woot", function(){
       console.log($(this).data("position"));
   });
});

</script>

You should see the position in the console if you are running it in a browser like Chrome, for example.

Alex J Gr
  • 83
  • 6