Skip to content
Permalink
Browse files

Quick improvement to the performace of .index() with no arguments - A…

…dding a unit test for .index() of a node without a parent returns -1
  • Loading branch information...
gnarf committed Jun 15, 2011
1 parent b43910a commit 9a96af1d59cc6a10b89b6f2489b04871a9c1c7fa
Showing with 14 additions and 7 deletions.
  1. +10 −5 src/traversing.js
  2. +4 −2 test/unit/traversing.js
@@ -145,12 +145,17 @@ jQuery.fn.extend({
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );

// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}

// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}

// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
@@ -99,9 +99,11 @@ test("is(jQuery)", function() {
});

test("index()", function() {
expect(1);
expect( 2 );

equals( jQuery("#text2").index(), 2, "Returns the index of a child amongst its siblings" )
equal( jQuery("#text2").index(), 2, "Returns the index of a child amongst its siblings" );

equal( jQuery("<div/>").index(), -1, "Node without parent returns -1" );
});

test("index(Object|String|undefined)", function() {

0 comments on commit 9a96af1

Please sign in to comment.
You can’t perform that action at this time.