Jai
Jai

Reputation: 2204

How can I get the index of an element within a jQuery object relative to the object?

If I have an object that is made up of multiple jQuery objects, that is:

var $listItems $('ul.list1 li').add($('ul.list2 li'));

How can I get the index of any element in the array, that is:

$listItems.click(function() {
    console.log($(this).index());
});

This isn't working for me as when an item from the second list is clicked obviously the index is the index relative to the DOM, not the jquery object.

How can I get the index?

http://jsfiddle.net/ZdCsu/

Upvotes: 0

Views: 77

Answers (2)

davids
davids

Reputation: 6371

What you could do is converting the jQuery object to an array:

var $listItems = $('ul.list1 li').add($('ul.list2 li'));

$listItems.click(function() {

    console.log($listItems.toArray().indexOf(this));

});​

Your updated jsfiddle

Upvotes: 1

Mitya
Mitya

Reputation: 34556

Relative indexing is always a bit of pain in jQuery because the elements in your stack may not have any logical relationship with regards to index.

You could do something like this:

$('#list_one li').add('#list_two li').each(function(index) {
    //assign a contrived index to each element in turn, relative to the stack
    $(this).data('stack-index', index);
}).on('click', function() {
    //then retrieve it on click
    alert($(this).data('stack-index'));
});

Also, in the specific example you poste, there's no need for add(), but perhaps in your real code there is.

Upvotes: 1

Related Questions