Skip to content
Permalink
Browse files

Add node and jQuery object support to $.fn.closest

  • Loading branch information...
timmywil
timmywil committed Mar 22, 2011
1 parent eb1497c commit e09d8898d8a8df27bb72ebc64a4cd08c11f21ddd
Showing with 26 additions and 8 deletions.
  1. +12 −8 src/traversing.js
  2. +14 −0 test/unit/traversing.js
@@ -32,6 +32,7 @@ jQuery.fn.extend({

var ret = this.pushStack( "", "find", selector ),
length, n, r;

for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
@@ -77,7 +78,8 @@ jQuery.fn.extend({

closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];


// Array
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
@@ -87,18 +89,18 @@ jQuery.fn.extend({
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];

if ( !matches[selector] ) {
matches[selector] = jQuery.expr.match.POS.test( selector ) ?
if ( !matches[ selector ] ) {
matches[ selector ] = POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}

while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[selector];
match = matches[ selector ];

if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
@@ -110,9 +112,11 @@ jQuery.fn.extend({

return ret;
}

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

// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;

for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
@@ -182,6 +182,20 @@ test("closest(Array)", function() {
same( jQuery("body").closest(["span","html"]), [{selector:"html", elem:document.documentElement, level:2}], "closest([body, html])" );
});

test("closest(jQuery)", function() {
expect(7);
var $child = jQuery("#nothiddendivchild"),
$parent = jQuery("#nothiddendiv"),
$main = jQuery("#main");
ok( $child.closest( $parent ).is('#nothiddendiv'), "closest( jQuery('#nothiddendiv') )" );
ok( $child.closest( $parent[0] ).is('#nothiddendiv'), "closest( jQuery('#nothiddendiv') ) :: node" );
ok( $child.closest( $child ).is('#nothiddendivchild'), "child is included" );
ok( $child.closest( $child[0] ).is('#nothiddendivchild'), "child is included :: node" );
equals( $child.closest( document.createElement('div') ).length, 0, "created element is not related" );
equals( $child.closest( $main ).length, 0, "Main not a parent of child" );
equals( $child.closest( $main[0] ).length, 0, "Main not a parent of child :: node" );
});

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

0 comments on commit e09d889

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