Skip to content

Commit

Permalink
Fix fn.closest() on collections of multiple elements
Browse files Browse the repository at this point in the history
The lookup needs to start on all elements of the collection
simultaneously and eliminate duplicated results as it traverses up the
DOM tree. Previously, the lookup only started at the 1st element of the
collection.

Fixes #1104
  • Loading branch information
mislav committed Jul 13, 2016
1 parent 85d475a commit 0f2ab27
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/zepto.js
Original file line number Diff line number Diff line change
Expand Up @@ -515,11 +515,13 @@ var Zepto = (function() {
return result
},
closest: function(selector, context){
var node = this[0], collection = false
if (typeof selector == 'object') collection = $(selector)
while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
node = node !== context && !isDocument(node) && node.parentNode
return $(node)
var nodes = [], collection = typeof selector == 'object' && $(selector)
this.each(function(_, node){
while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
node = node !== context && !isDocument(node) && node.parentNode
if (node && nodes.indexOf(node) < 0) nodes.push(node)
})
return $(nodes)
},
parents: function(selector){
var ancestors = [], nodes = this
Expand Down
7 changes: 7 additions & 0 deletions test/zepto.html
Original file line number Diff line number Diff line change
Expand Up @@ -1176,6 +1176,13 @@ <h1>Zepto Core unit tests</h1>
t.assertLength(0, el.closest('form'))
},

testClosestMultiple: function(t){
var els = $('#parents ul li')
var uls = els.closest('ul')
t.assertEqualCollection($('#parents ul'), uls)
t.assertEqualCollection($('#parents'), uls.closest('#parents'))
},

testClosestWithCollection: function(t){
var targets = $('#parents > li')
var result = $('#li2').closest(targets)
Expand Down

0 comments on commit 0f2ab27

Please sign in to comment.