Skip to content

Commit

Permalink
add .contents() .items()
Browse files Browse the repository at this point in the history
  • Loading branch information
gawel committed Nov 27, 2012
1 parent 1581e55 commit 0ca5ba5
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
2 changes: 1 addition & 1 deletion docs/css.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ You can play with css classes::
>>> p.addClass("toto")
[<p#hello.hello.toto>]
>>> p.toggleClass("titi toto")
[<p#hello.titi.hello>]
[<p#hello.hello.titi>]
>>> p.removeClass("titi")
[<p#hello.hello>]

Expand Down
39 changes: 33 additions & 6 deletions pyquery/pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,9 +259,23 @@ def __add__(self, other):
return self.__class__(self[:] + other[:])

def extend(self, other):
"""Extend with anoter PyQuery object"""
assert isinstance(other, self.__class__)
self._extend(other[:])

def items(self, selector=None):
"""Iter over elements. Return PyQuery objects:
>>> d = PyQuery('<div><span>foo</span><span>bar</span></div>')
>>> [i.text() for i in d.items('span')]
['foo', 'bar']
>>> [i.text() for i in d('span').items()]
['foo', 'bar']
"""
elems = selector and self(selector) or self
for elem in elems:
yield self.__class__(elem)

def __str__(self):
"""xml representation of current nodes::
Expand Down Expand Up @@ -477,6 +491,19 @@ def closest(self, selector=None):
result.append(current)
return self.__class__(result, **dict(parent=self))

def contents(self):
"""
Return contents (with text nodes):
>>> d = PyQuery('hello <b>bold</b>')
>>> d.contents() # doctest: +ELLIPSIS
['hello ', <Element b at ...>]
"""
results = []
for elem in self:
results.extend(elem.xpath('child::text()|child::*'))
return self.__class__(results, **dict(parent=self))

def filter(self, selector):
"""Filter elements in self using selector (string or function):
Expand Down Expand Up @@ -751,12 +778,12 @@ def toggleClass(self, value):
"""
for tag in self:
values = set(value.split(' '))
classes = set((tag.get('class') or '').split())
values_to_add = values.difference(classes)
classes.difference_update(values)
classes = classes.union(values_to_add)
classes.difference_update([''])
values = value.split(' ')
classes = (tag.get('class') or '').split()
values_to_add = [v for v in values if v not in classes]
values_to_del = [v for v in values if v in classes]
classes = [v for v in classes if v not in values_to_del]
classes += values_to_add
tag.set('class', ' '.join(classes))
return self

Expand Down

0 comments on commit 0ca5ba5

Please sign in to comment.