1

Suppose I have the following HTML:

<div id="Container">
    <div class="TheClass"></div>
    <div class="TheOtherClass"></div>
    <div class="TheClass"></div>
    <div class="TheOtherClass"></div>
    <div class="TheClass"></div>
    <div class="TheOtherClass"></div>
</div>

As you can see, I have two classes alternating. I want to pass the index of the class TheClass in terms of its occurrence inside the container.

If I write:

$('#Container').on({
   click: function () { SomeFunction($(this).index()); }
}, '.TheClass');

and click on the last element TheClass, the parameter passed will be 5 but I want to receive 3 because the last TheClass element is the third occurrence. How can I do that?

2 Answers 2

5

Try the index() variant that takes an selector as parameter

$('#Container').on({
    click: function () {
        SomeFunction($(this).index('#Container .TheClass'));
    }
}, '.TheClass');

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Just define your index in terms of the the class you're trying to reference:

    $('#Container').on({
        click: function () { 
            SomeFunction($(this).index("." + $(this).attr('class')) + 1);
        }
    }, '.TheClass');

This way, your code is DRYer and more portable.

Comments

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.