Bug Tracker

Opened 14 years ago

Closed 14 years ago

Last modified 14 years ago

#3971 closed enhancement (fixed)

.index() enhancement

Reported by: ajpiano Owned by: brandon
Priority: major Milestone: 1.4
Component: core Version: 1.3.1
Keywords: Cc:
Blocked by: Blocking:

Description (last modified by brandon)

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.

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() );


as per: http://groups.google.com/group/jquery-dev/browse_thread/thread/f5e07e2f81011d8b

Attachments (2)

index_enhancement.js (411 bytes) - added by ajpiano 14 years ago.
index.2009.03.05.patch (2.0 KB) - added by paul.irish 14 years ago.
a proper patch with testcases.

Download all attachments as: .zip

Change History (7)

Changed 14 years ago by ajpiano

Attachment: index_enhancement.js added

Changed 14 years ago by paul.irish

Attachment: index.2009.03.05.patch added

a proper patch with testcases.

comment:1 Changed 14 years ago by paul.irish

Just added a proper patch. Comes with four unit tests, as well.

One thing I recognized while cleaning this up is that in this case, passing a selector into index() vs passing an jquery object of those same elements will give different results.

Because index() can't determine if you're passing a jquery object as an argument because you'd want to see the relative index, or you want to use the legacy implementation of elems.index($(this))

This is a weird break in the expected API, so it may be worth either: a) removing the $(this).index(selector) functionality b) renaming this enhanced method .indexWithin() or something.

I still feel strongly that providing the $(this).index() technique is a valuable (and very jquery-like) addition.

Curious what others think about this.

comment:2 Changed 14 years ago by brandon

Description: modified (diff)

comment:3 Changed 14 years ago by brandon

Owner: set to brandon

comment:4 Changed 14 years ago by brandon

Resolution: fixed
Status: newclosed

While I can understand the potential confusion about passing a jQuery collection vs a selector. This is something that can be cleared up with proper documentation.

Added in r6330.

comment:5 Changed 14 years ago by ajpiano

woo, thanks for taking care of this.

Note: See TracTickets for help on using tickets.