Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions pyquery/pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -1300,6 +1300,10 @@ def after(self, value):
if i > 0:
root = deepcopy(list(root))
parent = tag.getparent()
if parent is None:
raise ValueError(
'Cannot add a sibling after an element without a '
'parent')
index = parent.index(tag) + 1
parent[index:index] = root
root = parent[index:len(root)]
Expand All @@ -1324,12 +1328,20 @@ def before(self, value):
previous.tail += root_text
else:
parent = tag.getparent()
if parent is None:
raise ValueError(
'Cannot add a sibling before an element without '
'a parent')
if not parent.text:
parent.text = ''
parent.text += root_text
if i > 0:
root = deepcopy(list(root))
parent = tag.getparent()
if parent is None:
raise ValueError(
'Cannot add a sibling before an element without a '
'parent')
index = parent.index(tag)
parent[index:index] = root
root = parent[index:len(root)]
Expand Down
25 changes: 25 additions & 0 deletions tests/test_pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,31 @@ def test_class(self):
d.removeClass('xx')
assert 'class' not in str(d), str(d)

def test_replace_with_on_child(self):
# documented working case: replace_with on a child found via
# .find(), which has a parent
doc = pq("<html><div /></html>")
node = pq("<span />")
child = doc.find('div')
child.replace_with(node)
assert str(doc) == '<html><span/></html>'

def test_replace_with_on_parentless_root_raises(self):
# calling replace_with() (which uses before() internally) on an
# element with no parent should raise a clear error instead of
# an AttributeError
doc = pq("<html><div /></html>")
node = pq("<span />")
self.assertRaises(ValueError, doc.replace_with, node)

def test_before_on_parentless_root_raises(self):
doc = pq("<html><div /></html>")
self.assertRaises(ValueError, doc.before, '<span />')

def test_after_on_parentless_root_raises(self):
doc = pq("<html><div /></html>")
self.assertRaises(ValueError, doc.after, '<span />')

def test_val_for_inputs(self):
d = pq(self.html2)
self.assertIsNone(d('input[name="none"]').val())
Expand Down