Skip to content

Commit

Permalink
add fn.parents() method
Browse files Browse the repository at this point in the history
  • Loading branch information
mislav committed Dec 28, 2010
1 parent 784de34 commit 329dda9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.rdoc
Expand Up @@ -48,6 +48,7 @@ Context and .find calls are equivalent:


find('selector'): find all children/grandchildren that match the given selector find('selector'): find all children/grandchildren that match the given selector
closest('selector'): find the first matching element by going upwards starting from the current element closest('selector'): find the first matching element by going upwards starting from the current element
parents('selector'): get all ancestors of elements in collection, optionally filtered by a selector
parent(): immediate parent node of each element in collection parent(): immediate parent node of each element in collection
next(): next siblings next(): next siblings
prev(): previous siblings prev(): previous siblings
Expand Down
12 changes: 12 additions & 0 deletions src/zepto.js
Expand Up @@ -76,6 +76,18 @@ var Zepto = (function() {
while(node && node !== document && nodes.indexOf(node) < 0) node = node.parentNode; while(node && node !== document && nodes.indexOf(node) < 0) node = node.parentNode;
return $(node); return $(node);
}, },
parents: function(selector){
var ancestors = [], nodes = this.get();
while (nodes.length > 0)
nodes = compact(nodes.map(function(node){
if ((node = node.parentNode) && node !== document && ancestors.indexOf(node) < 0) {
ancestors.push(node);
return node;
}
}));
ancestors = $(ancestors);
return selector === undefined ? ancestors : ancestors.filter(selector);
},
parent: function(selector){ parent: function(selector){
var node, nodes = []; var node, nodes = [];
this.each(function(el){ this.each(function(el){
Expand Down
14 changes: 14 additions & 0 deletions test/zepto.html
Expand Up @@ -345,6 +345,20 @@ <h1>Zepto DOM unit tests</h1>
t.assertLength(0, el.closest('div')); t.assertLength(0, el.closest('div'));
}, },


testParents: function(t){
var body = document.body, html = body.parentNode, container = $('#parents');
t.assertEqualCollection($([body, html]), container.parents());

var expected = $('#li1 > ul').get();
expected.push($('#li1').get(0));
expected.push(container.get(0));
expected = expected.concat([body, html]);
t.assertEqualCollection($(expected), $('#li1').find('li').parents());

expected = [$('#nested').get(0), $('#parents').get(0)];
t.assertEqualCollection($(expected), $('#li2').parents('ul'));
},

testParent: function(t){ testParent: function(t){
var el = $('#li1'); var el = $('#li1');
t.assertEqualCollection($('#parents'), el.parent()); t.assertEqualCollection($('#parents'), el.parent());
Expand Down

0 comments on commit 329dda9

Please sign in to comment.