Skip to content
Permalink
Browse files

Added in the new .closest(Array) method, will be used to improve the …

…performance of live filtering.
  • Loading branch information
jeresig committed Dec 3, 2009
1 parent 62436f4 commit e534a310c7e99c44d93855ad5865ad5e985039ba
Showing with 42 additions and 9 deletions.
  1. +31 −9 src/traversing.js
  2. +11 −0 test/unit/traversing.js
@@ -54,21 +54,43 @@ jQuery.fn.extend({
return this.pushStack( winnow(this, selector, true), "filter", selector );
},

closest: function( selector, context ) {
var pos = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) : null;
closest: function( selectors, context ) {
if ( jQuery.isArray( selectors ) ) {
var ret = [], cur = this[0], selector;

if ( cur ) {
for ( var i = 0, l = selectors.length; i < l; i++ ) {
selectors[i] = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selectors[i];
}

while ( cur && cur.ownerDocument && cur !== context ) {
for ( var i = 0; i < selectors.length; i++ ) {
selector = selectors[i];
if ( selector.jquery ? selector.index(cur) > -1 : jQuery(cur).is(selector) ) {
selector = selector.selector || selector;
ret.push({ selector: selector, elem: cur });
selectors.splice(i--, 1);
}
}
cur = cur.parentNode;
}
}

return ret;
}

var pos = jQuery.expr.match.POS.test( selectors ) ?
jQuery( selectors, context || this.context ) : null;

return this.map(function(){
var cur = this, closer = 0;
return this.map(function(i, cur){
while ( cur && cur.ownerDocument && cur !== context ) {
if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
jQuery.lastCloser = closer;
if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) {
return cur;
}
cur = cur.parentNode;
closer++;
}
jQuery.lastCloser = -1;
return null;
});
},
@@ -107,6 +107,17 @@ test("closest()", function() {
same( jq.closest("#nothiddendiv", document.body).get(), q("nothiddendiv"), "Context not reached." );
});

test("closest(Array)", function() {
expect(6);
same( jQuery("body").closest(["body"]), [{selector:"body", elem:document.body}], "closest([body])" );
same( jQuery("body").closest(["html"]), [{selector:"html", elem:document.documentElement}], "closest([html])" );
same( jQuery("body").closest(["div"]), [], "closest([div])" );
same( jQuery("#main").closest(["span,#html"]), [{selector:"span,#html", elem:document.documentElement}], "closest([span,#html])" );

same( jQuery("body").closest(["body","html"]), [{selector:"body", elem:document.body}, {selector:"html", elem:document.documentElement}], "closest([body, html])" );
same( jQuery("body").closest(["span","html"]), [{selector:"html", elem:document.documentElement}], "closest([body, html])" );
});

test("not(Selector)", function() {
expect(7);
equals( jQuery("#main > p#ap > a").not("#google").length, 2, "not('selector')" );

0 comments on commit e534a31

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