diff options
author | Leonard Richardson <leonard.richardson@canonical.com> | 2012-02-07 18:01:06 -0500 |
---|---|---|
committer | Leonard Richardson <leonard.richardson@canonical.com> | 2012-02-07 18:01:06 -0500 |
commit | b32c88cc0362030f2801690aca695cf5d3d57f55 (patch) | |
tree | 178e61a52eb0c2c295dc78a6a0bf6ca681a38eff /bs4/element.py | |
parent | f23376fdeee206cbf24d4b3aff43a307fb3786a6 (diff) |
Added and tested insert_before and insert_after.
Diffstat (limited to 'bs4/element.py')
-rw-r--r-- | bs4/element.py | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/bs4/element.py b/bs4/element.py index b176777..478d285 100644 --- a/bs4/element.py +++ b/bs4/element.py @@ -190,6 +190,34 @@ class PageElement(object): """Appends the given tag to the contents of this tag.""" self.insert(len(self.contents), tag) + def insert_before(self, successor): + """Makes this element the immediate predecessor of the given element. + + The two elements will have the same parent, and this element + will be immediately before the given one. + """ + parent = successor.parent + if parent is None: + raise ValueError( + "Destination has no parent, so 'before' has no meaning.") + self.extract() + index = parent.index(successor) + parent.insert(index, self) + + def insert_after(self, predecessor): + """Makes this element the immediate successor of the given element. + + The two elements will have the same parent, and this element + will be immediately after the given one. + """ + parent = predecessor.parent + if parent is None: + raise ValueError( + "Destination has no parent, so 'after' has no meaning.") + self.extract() + index = parent.index(predecessor) + parent.insert(index+1, self) + def find_next(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" |