From cae93c39eb57ccc2acc5e101eda7a56e0a734cdf Mon Sep 17 00:00:00 2001
From: John Resig <jeresig@gmail.com>
Date: Sat, 25 Jul 2009 21:31:59 +0000
Subject: [PATCH] Implemented support for .context limited .closest() calls.
 Fixes #4072.

---
 src/traversing.js       |    7 ++++---
 test/unit/traversing.js |    8 +++++++-
 2 files changed, 11 insertions(+), 4 deletions(-)

diff --git a/src/traversing.js b/src/traversing.js
index 669c70a..e8a8938 100644
--- a/src/traversing.js
+++ b/src/traversing.js
@@ -53,11 +53,12 @@ jQuery.fn.extend({
 
 	closest: function( selector ) {
 		var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
-			closer = 0;
+			closer = 0,
+			context = this.context;
 
 		return this.map(function(){
 			var cur = this;
-			while ( cur && cur.ownerDocument ) {
+			while ( cur && cur.ownerDocument && cur !== context ) {
 				if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
 					jQuery.data(cur, "closest", closer);
 					return cur;
@@ -120,4 +121,4 @@ jQuery.each({
 
 		return this.pushStack( jQuery.unique( ret ), name, selector );
 	};
-});
\ No newline at end of file
+});
diff --git a/test/unit/traversing.js b/test/unit/traversing.js
index f585d9c..16f6043 100644
--- a/test/unit/traversing.js
+++ b/test/unit/traversing.js
@@ -91,7 +91,7 @@ test("filter(jQuery)", function() {
 })
 
 test("closest()", function() {
-	expect(6);
+	expect(9);
 	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)" );
@@ -99,6 +99,12 @@ test("closest()", function() {
 
 	isSet( jQuery("div:eq(1)").closest("div:first").get(), [], "closest(div:first)" );
 	isSet( jQuery("div").closest("body:first div:last").get(), q("fx-tests"), "closest(body:first div:last)" );
+
+	// Test .closest() limited by the context
+	var jq = jQuery("#nothiddendivchild", document.body);
+	isSet( jq.closest("html").get(), [], "Context limited." );
+	isSet( jq.closest("body").get(), [], "Context limited." );
+	isSet( jq.closest("#nothiddendiv").get(), q("nothiddendiv"), "Context not reached." );
 });
 
 test("not(Selector)", function() {
-- 
1.7.10.4