Last active
April 14, 2016 15:47
-
-
Save RubaXa/6593747 to your computer and use it in GitHub Desktop.
Fastest jQuery.fn.find
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Fastest jQuery.fn.find | |
* @jsperf http://jsperf.com/jquery-find-vs-jquery-fastestfind | |
* @author RubaXa <[email protected]> | |
* @license MIT | |
*/ | |
/* global document, jQuery */ | |
document.createElement('div').querySelectorAll && (function ($, originalFind){ | |
var rbuggyQSA = /[>+~*&|:!=?;]|[\w\]]\s+[\[#.\w]|^#\d/; | |
/** | |
* Find elements | |
* @param {String|jQuery|HTMLElement} selector | |
* @returns {jQuery} | |
*/ | |
$.fn.find = function (selector){ | |
if( (typeof selector === 'string') && !rbuggyQSA.test(selector) ){ | |
var ret = this.pushStack([], 'find', selector), el, length; | |
for( var i = 0, l = this.length; i < l; i++ ){ | |
el = this[i]; | |
length = ret.length; | |
if( el && el.querySelectorAll ){ | |
var res = el.querySelectorAll(selector); | |
if( res.length ){ | |
for( var j = 0, jn = res.length; j < jn; j++ ){ | |
ret[length+j] = res[j]; | |
ret.length++; | |
} | |
} | |
if( i > 0 ){ | |
// jQuery: Make sure that the results are unique | |
for( var n = length; n < ret.length; n++ ){ | |
for( var r = 0; r < length; r++ ){ | |
if( ret[r] === ret[n] ){ | |
ret.splice(n--, 1); | |
break; | |
} | |
} | |
} | |
} | |
} | |
} | |
return ret; | |
} | |
return originalFind.call(this, selector); | |
}; | |
})(jQuery, jQuery.fn.find); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment