Skip to content

Commit

Permalink
Merge pull request #367 from gnarf37/index-optimize
Browse files Browse the repository at this point in the history
Quick improvement to the performance of .index() with no arguments
  • Loading branch information
dmethvin committed Aug 4, 2011
2 parents 8d5c874 + 9a96af1 commit 3cfb134
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
15 changes: 10 additions & 5 deletions src/traversing.js
Expand Up @@ -145,12 +145,17 @@ jQuery.fn.extend({
// Determine the position of an element within // Determine the position of an element within
// the matched set of elements // the matched set of elements
index: function( elem ) { index: function( elem ) {
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0], // No argument, return index in parent
// If it receives a string, the selector is used if ( !elem ) {
// If it receives nothing, the siblings are used return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
elem ? jQuery( elem ) : this.parent().children() ); }

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

// Locate the position of the desired element // Locate the position of the desired element
return jQuery.inArray( return jQuery.inArray(
// If it receives a jQuery object, the first element is used // If it receives a jQuery object, the first element is used
Expand Down
6 changes: 4 additions & 2 deletions test/unit/traversing.js
Expand Up @@ -99,9 +99,11 @@ test("is(jQuery)", function() {
}); });


test("index()", 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() { test("index(Object|String|undefined)", function() {
Expand Down

0 comments on commit 3cfb134

Please sign in to comment.