Skip to content

Commit

Permalink
No-op remove() on orphan nodes
Browse files Browse the repository at this point in the history
As suggested in #1898
  • Loading branch information
jhy committed Feb 21, 2023
1 parent 62de0a1 commit da5e977
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
jsoup changelog

Release 1.16.1 [PENDING]
* Improvement: Calling Node.remove() on a node with no parent is now a no-op, vs a validation error.
<https://github.com/jhy/jsoup/issues/1898>

* Bugfix: Corrected support for ruby elements (<ruby>, <rp>, <rt>, and <rtc>) to current spec.
<https://github.com/jhy/jsoup/issues/1294>

Expand Down
7 changes: 4 additions & 3 deletions src/main/java/org/jsoup/nodes/Node.java
Original file line number Diff line number Diff line change
Expand Up @@ -315,11 +315,12 @@ public Node root() {
}

/**
* Remove (delete) this node from the DOM tree. If this node has children, they are also removed.
* Remove (delete) this node from the DOM tree. If this node has children, they are also removed. If this node is
* an orphan, nothing happens.
*/
public void remove() {
Validate.notNull(parentNode);
parentNode.removeChild(this);
if (parentNode != null)
parentNode.removeChild(this);
}

/**
Expand Down
8 changes: 8 additions & 0 deletions src/test/java/org/jsoup/nodes/NodeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ public void handlesAbsOnProtocolessAbsoluteUris() {
assertEquals("<span>two</span> three", TextUtil.stripNewlines(p.html()));
}

@Test void removeOnOrphanIsNoop() {
// https://github.com/jhy/jsoup/issues/1898
Element node = new Element("div");
assertNull(node.parentNode());
node.remove();
assertNull(node.parentNode());
}

@Test public void testReplace() {
Document doc = Jsoup.parse("<p>One <span>two</span> three</p>");
Element p = doc.select("p").first();
Expand Down

0 comments on commit da5e977

Please sign in to comment.