Skip to content

Commit a2bd8a5

Browse files
committed
.closest() should return a unique set of elements, not duplicates of the same ancestor. Fixes #6700
1 parent 6a0942c commit a2bd8a5

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/traversing.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,10 @@ jQuery.fn.extend({
5353
},
5454

5555
closest: function( selectors, context ) {
56+
var ret;
5657
if ( jQuery.isArray( selectors ) ) {
57-
var ret = [], cur = this[0], match, matches = {}, selector, level = 1;
58-
58+
var cur = this[0], match, matches = {}, selector, level = 1;
59+
ret = [];
5960
if ( cur && selectors.length ) {
6061
for ( var i = 0, l = selectors.length; i < l; i++ ) {
6162
selector = selectors[i];
@@ -80,13 +81,12 @@ jQuery.fn.extend({
8081
}
8182
}
8283

83-
return ret;
84+
return ret.length > 1 ? jQuery.unique(ret) : ret;
8485
}
8586

8687
var pos = jQuery.expr.match.POS.test( selectors ) ?
8788
jQuery( selectors, context || this.context ) : null;
88-
89-
return this.map(function( i, cur ) {
89+
ret = jQuery.map(this.get(),function( cur,i ) {
9090
while ( cur && cur.ownerDocument && cur !== context ) {
9191
if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) {
9292
return cur;
@@ -95,6 +95,10 @@ jQuery.fn.extend({
9595
}
9696
return null;
9797
});
98+
99+
ret = ret.length > 1 ? jQuery.unique(ret) : ret;
100+
101+
return this.pushStack( ret, "closest", selectors );
98102
},
99103

100104
// Determine the position of an element within

test/unit/traversing.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ test("filter(jQuery)", function() {
120120
})
121121

122122
test("closest()", function() {
123-
expect(9);
123+
expect(10);
124124
same( jQuery("body").closest("body").get(), q("body"), "closest(body)" );
125125
same( jQuery("body").closest("html").get(), q("html"), "closest(html)" );
126126
same( jQuery("body").closest("div").get(), [], "closest(div)" );
@@ -134,6 +134,10 @@ test("closest()", function() {
134134
same( jq.closest("html", document.body).get(), [], "Context limited." );
135135
same( jq.closest("body", document.body).get(), [], "Context limited." );
136136
same( jq.closest("#nothiddendiv", document.body).get(), q("nothiddendiv"), "Context not reached." );
137+
138+
//Test that .closest() returns unique'd set
139+
equals( jQuery('#main p').closest('#main').length, 1, "Closest should return a unique set" );
140+
137141
});
138142

139143
test("closest(Array)", function() {

0 commit comments

Comments
 (0)