How do I get the current position of a div by its class?

9

For example:

<div class="container">
  <div class="position"></div> <!-- Essa tinha que ser position [0]-->
  <div class="position"></div> <!-- Essa tinha que ser position [1]-->
  <div class="other"></div>
  <div class="position"></div> <!-- Essa tinha que ser position [2]-->
  <div class="position"></div> <!-- Essa tinha que ser position [3]-->
  <div class="other"></div>
  <div class="position"></div> <!-- Essa tinha que ser position [4]-->
  <div class="other"></div>
  <div class="other"></div>
</div>

This is preferably done with Jquery.

Is it possible?

    
asked by anonymous 20.02.2014 / 20:19

3 answers

5

You can use this:

var divs = $('.container .position');
divs.each(function (i) {
    this.setAttribute('data-index', i);
});
divs.on('click', function () {
    console.log($(this).data('index'));
});

Example

In case you want to know the last div you can use so

There is another variant:

var divs = $('.container .position');
divs.on('click', function () {
   var pos = (divs.get()).indexOf(this);
   // ou, à la Zuulvaretto:
   // var pos = Array.prototype.indexOf.call(divs, this);
    console.log(pos);
});

Example

    
20.02.2014 / 21:12
2

You can select the elements via jQuery. The array will be in the order that they appear in the DOM . p>

$(".position").each(function(index, el) {
    $(this).text("Pos: " + index);
});

Fiddle

    
20.02.2014 / 20:25
0

You can use the index() function of jQuery, working as follows, in your case I will illustrate with a click event:

$('.position').click(function(){
  alert($(this).index());
}); 
    
20.02.2014 / 20:23