FlyingCat
FlyingCat

Reputation: 14250

How to find the position of the certain element inside a div?

I am trying to find the image position inside my div

my Html

<div>
  <p>test</p>
  <img src='test1.jpg'/>  
  <p>test</p>
  <p>test</p>  
  <img src='test2.jpg'/>  
  <p>test</p>
  <img src='test2.jpg'/>  --the user clicks this image and I want to know the time it appears. In this case, 2 is what I need.
  <p>test</p>
  <img src='test2.jpg'/>
  <p>test</p>
</div>

I have

var imagePosition=0;
$('img').click(function(){
     var imgSource=$(this).attr('src');
    $(this).closest('div').find('img').each(function(){
       if($(this).attr('src')==imgSource){
          imagePosition++;
       }
    })
})

I can find out how many time the same images appear but I can't tell which image the user clicks and it's position. Are there anyways to do this? Thanks so much!

Upvotes: 1

Views: 159

Answers (2)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70139

$('img').click(function() {
    var clickedIndex = $('img[src="'+ $(this).attr('src') +'"]').index(this) + 1;
    console.log(clickedIndex);
});

Fiddle

Here I built an attribute search of images with the same source attribute as the clicked one, then call .index(element) passing the clicked element as reference. As index is 0-based, we add 1.

If having the same ancestor div is important, just adapt it with closest and find as was initially:

var clickedIndex = 
     $(this).closest('div')
    .find('img[src="'+ $(this).attr('src') +'"]').index(this) + 1;

Updated fiddle


To get a reference to the clicked image, just use the this keyword inside the handler. You can wrap it inside a jQuery object $(this) and call jQuery methods on it then.


Also, by your question's code comment, I assume that by position you actually mean the index of the element, but if you'd rather get the literal position of the element you can use the .offset() (relative to document) and .position() (relative to parent) methods.

Side-note: If you need to count the number of images with the same source, you can do it in a much easier way with .length:

var countImages = $('img[src="'+ $(this).attr('src') +'"]').length;

Again, the above assumes to be inside an event handler's scope where this references an image element. You can easily adapt it to query for any src though.

Upvotes: 3

YogeshWaran
YogeshWaran

Reputation: 2281

You can use index

   $('img').click(function(){

         index =  $(this).closest('div').find('img').index(this) + 1;

   });

Upvotes: 1

Related Questions