From 1a91aac56176edcb2327569feb5aff5282f8cacb Mon Sep 17 00:00:00 2001 From: Jonathan Hedley Date: Mon, 25 Nov 2024 20:16:32 +1100 Subject: [PATCH] Use the incoming node's parent if outgoing has already been removed Fixes #2212 This won't work for all scenarios - when an element is removed it is de-parented, and so if the order of calls had lead to both elements already being detached, there won't be a parent to re-attach to. --- CHANGES.md | 2 ++ src/main/java/org/jsoup/nodes/Node.java | 1 + src/test/java/org/jsoup/nodes/NodeTest.java | 5 +---- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index aca421e5a6..b3c11ebf54 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -15,6 +15,8 @@ * In the `TreeBuilder`, the `onNodeInserted()` and `onNodeClosed()` events are now also fired for the outermost / root `Document` node. This enables source position tracking on the Document node (which was previously unset). And it also enables the node traversor to see the outer Document node. [2182](https://github.com/jhy/jsoup/pull/2182) +* Selected Elements can now be position swapped inline using + `Elements#set()`. [2212](https://github.com/jhy/jsoup/issues/2212) ### Bug Fixes diff --git a/src/main/java/org/jsoup/nodes/Node.java b/src/main/java/org/jsoup/nodes/Node.java index 2e9d66f089..0bd18c33af 100644 --- a/src/main/java/org/jsoup/nodes/Node.java +++ b/src/main/java/org/jsoup/nodes/Node.java @@ -509,6 +509,7 @@ void nodelistChanged() { */ public void replaceWith(Node in) { Validate.notNull(in); + if (parentNode == null) parentNode = in.parentNode; // allows old to have been temp removed before replacing Validate.notNull(parentNode); parentNode.replaceChild(this, in); } diff --git a/src/test/java/org/jsoup/nodes/NodeTest.java b/src/test/java/org/jsoup/nodes/NodeTest.java index 0675f7b27e..727e68711c 100644 --- a/src/test/java/org/jsoup/nodes/NodeTest.java +++ b/src/test/java/org/jsoup/nodes/NodeTest.java @@ -176,11 +176,8 @@ public void handlesAbsOnProtocolessAbsoluteUris() { assertEquals("One foo three", p.html()); } - /** - * test case for - * Issue #2212 - */ @Test public void testReplaceTwice() { + // https://github.com/jhy/jsoup/issues/2212 Document doc = Jsoup.parse("

Child OneChild TwoChild ThreeChild Four

"); Elements children = doc.select("p").first().children(); // first swap 0 and 1