2

I think I need to use jQuery's index() function but I'm doing it all wrong! I have a bunch of table cells with images inside, and one of them will have a class called "current". How can I tell which image has the class? I need an integer to work with.

I'm thinking something like this but I get "-1", nothing found..

var prev = $('#full_width_gallery').index('img');

Any ideas where I'm going wrong?

3
  • 1
    How about $('img.current')? Commented Oct 18, 2012 at 16:32
  • In the index()function? That doesn't work. Commented Oct 18, 2012 at 16:33
  • @Dan Oh I see.. I thought you were trying to select the image seeing How can I tell which image has the class. Commented Oct 18, 2012 at 16:34

1 Answer 1

4
  1. Select the images: var $images = $('#full_width_gallery img');

  2. Retrieve the index of the image with class ".current": $images.filter('.current').index(); - this will be the index of that image in $images, not some kind of "global" index!

In total:

var index = $('#full_width_gallery img').filter('.current').index();

or:

var index = $('.current').index('#full_width_gallery img');
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a reason to create a var, or would it be just as effective doing $('#full_width_gallery img').index('.current');?
Could I use that like this; var $images = $('#full_width_gallery img'); var current = $images.index('.current'); alert(current)
@Archer That's the same, I just introduced the variable to break it up in two steps.
.index does not work like that. You swapped the order of object/argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.