Commits

Anonymous committed 298d538

added closest() method

Comments (0)

Files changed (2)

pyquery/pyquery.py

         elements = [child for tag in self for child in tag.getchildren()]
         return self._filter_only(selector, elements)
 
+    def closest(self, selector=None):
+        """
+            >>> d = PyQuery('<div class="hello"><p>This is a <strong class="hello">test</strong></p></div>')
+            >>> d('strong').closest('div')
+            [<div.hello>]
+            >>> d('strong').closest('.hello')
+            [<strong.hello>]
+            >>> d('strong').closest('form')
+            []
+        """
+        try:
+            current = self[0]
+        except IndexError:
+            current = None
+        while current is not None and not self.__class__(current).is_(selector):
+            current = current.getparent()
+        return self.__class__(current, **dict(parent=self))
+
     def filter(self, selector):
         """Filter elements in self using selector (string or function).
 
         assert len(self.klass('div', self.html).find('span').end()) == 2
         assert len(self.klass('#node2', self.html).find('span').end()) == 1
 
+    def test_closest(self):
+        assert len(self.klass('#node1 span', self.html).closest('body')) == 1
+        assert self.klass('#node2', self.html).closest('.node3').attr('id') == 'node2'
+        assert self.klass('.node3', self.html).closest('form') == []
 
 class TestOpener(unittest.TestCase):
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.