0

If I have a list of items:

<div id="list">
  <div class="good">first</div>
  <div class="good">second</div>
  <div>trash</div>
  <div class="good">third</div>
</div>

and I set a bind:

$(document).ready(function () {
    $("#list").children(".good").click(function () {
        var index = getIndex(this);
        alert(index);
    });
});

How may I determine the index of the clicked item such that first would alert 0, second: 1 and third: 2 when clicked on?

I tried something similar to but it returns -1 every time.:

function getIndex(obj) {
    var $objectArray = $("#list").children(".good");
    return $.inArray($(obj), $objectArray);

Any Ideas?

Oh, Fiddle is here: http://jsfiddle.net/Sh9Dt/

Slight edit to add another garbage list, I need it in relation to a specific jquery select.

Working JSFiddle thanks to @adeneo: http://jsfiddle.net/Sh9Dt/1/

Jeff
  • 480
  • 1
  • 5
  • 17
  • 6
    Use the `index` method, `$(this).index()`. – Ram Jul 30 '14 at 16:58
  • 1
    You're trying to make something that jQuery already has built in, just do `var index = $("#list").children().index(this)` – adeneo Jul 30 '14 at 17:00
  • @adeneo That's what I was looking for. Feel free to post it as an answer and I'll accept. Funny I never saw the index method for jquery before. – Jeff Jul 30 '14 at 17:03

0 Answers0