From 6b090328643988869e2288a4874935680d8573ca Mon Sep 17 00:00:00 2001 From: John Resig Date: Mon, 22 Dec 2008 00:52:53 +0000 Subject: [PATCH] Added support for the new .closest() method (very useful for event delegation). --- src/core.js | 11 +++++++++++ test/unit/core.js | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/src/core.js b/src/core.js index 7ddb2c5..ff8114b 100644 --- a/src/core.js +++ b/src/core.js @@ -338,6 +338,17 @@ jQuery.fn = jQuery.prototype = { }) ), "filter", selector ); }, + closest: function( selector ) { + return this.map(function(){ + var cur = this; + while ( cur && cur.ownerDocument ) { + if ( jQuery(cur).is(selector) ) + return cur; + cur = cur.parentNode; + } + }); + }, + not: function( selector ) { if ( typeof selector === "string" ) // test special case where just one selector is passed in diff --git a/test/unit/core.js b/test/unit/core.js index 536e58c..1ae2dfa 100644 --- a/test/unit/core.js +++ b/test/unit/core.js @@ -1309,6 +1309,14 @@ test("filter()", function() { equals( j.filter("[name]").length, 0, "Check node,textnode,comment to filter the one span" ); }); +test("closest()", function() { + expect(4); + isSet( jQuery("body").closest("body").get(), q("body"), "closest(body)" ); + isSet( jQuery("body").closest("html").get(), q("html"), "closest(html)" ); + isSet( jQuery("body").closest("div").get(), [], "closest(div)" ); + isSet( jQuery("#main").closest("span,#html").get(), q("html"), "closest(span,#html)" ); +}); + test("not()", function() { expect(8); equals( jQuery("#main > p#ap > a").not("#google").length, 2, "not('selector')" ); -- 1.7.10.4