Bug Tracker

Opened 10 years ago

Closed 10 years ago

Last modified 10 years ago

#13347 closed bug (notabug)

index( undefined ) returning incorrect values

Reported by: Motty Owned by:
Priority: undecided Milestone: None
Component: traversing Version:
Keywords: Cc:
Blocked by: Blocking:


The index of an undefined element should return -1, but instead returns an incorrect value (http://jsfiddle.net/Mottie/FMh69/)

// jQuery ver = value returned
// 1.6.4   = 2
// 1.7.2   = 2
// 1.8.3   = 2
// 1.9.0   = 0
// 2.0.0b1 = 0
var undef;
console.log( $('div').index( undef ) );

Change History (3)

comment:1 Changed 10 years ago by dmethvin

I feel it's important to point out that an undefined value is not one of the four things that .index() is documented to take: no arguments, a selector string, a DOM element, or a jQuery collection. So there is no "should" here, although we might decide to define new behavior. It looks like up until 1.9 it was being interpreted as the "no arguments" case. -- Correction, it *is* the no-args case but there was a bug before 1.9.

Last edited 10 years ago by dmethvin (previous) (diff)

comment:2 Changed 10 years ago by gibson042

Component: unfiledtraversing
Resolution: notabug
Status: newclosed

The behavior change you observe stems from fixing #10977, but the invalid input undefined was treated like "no argument" (returns position in parent of the collection's first member) even before then. You probably want to do something like element ? $collection.index( element ) : -1.

comment:3 in reply to:  1 Changed 10 years ago by Motty

I was just troubleshooting some code that was passing an undefined variable to the index. I'll just make sure to follow gibson042's recommendation from now on, thanks! :)

Note: See TracTickets for help on using tickets.