.index() enhancement

.index() enhancement


It would be useful to be able to use the .index() method to find the
index of the current element in a given set, rather than the current
implementation (searching the current set for a given element), which
forces the developer to do gyrations in order to find out a simple
piece of info.
For instance
$("#sometable th img").click(function() {
//find out index of img's parent <th> in its own <tr>
var $th = $(this).parent();
//now we have a few not so great choices
//1.
var index = $("#sometable thead tr).index($th);
//2.
var index = $th.parent().children().index($th);
//3. doesn't even work, but many would assume it would, and it
doesn't!)
// because the desired element is always the last one in the set.
var index = $th.siblings().andSelf().index($th);
});
Paul Irish and I propose the following enhancement, which is rough and
we welcome any suggestions...
jQuery.fn.index = function(elem){
// legacy implementation
if ( typeof elem === 'object'){
return jQuery.inArray(
elem && elem.jquery ? elem[0] : elem
, this );
}
//return the index of the element in a new jQuery obj from selector,
or by default, amongst its own siblings.
return jQuery.inArray(this[0],
elem ? jQuery(elem) : this.parent().children() );
};
which would allow for the following.
$("#sometable th img").click(function() {
//find out index of img's parent <th> in its own <tr>
var index = $(this).parent().index();
//for sake of example, index of image in set of all images.
var imgIndex = $(this).index("img");
});
If people think this is worthwhile, we will post an enhancement
ticket. Thoughts?