Navigation Menu

Skip to content

Commit

Permalink
Added Node#remove and Node#replaceWith.
Browse files Browse the repository at this point in the history
Closes #19
  • Loading branch information
jhy committed Jul 2, 2011
1 parent fcab98c commit 982e4f9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGES
@@ -1,6 +1,9 @@
jsoup changelog

*** Release 0.3.2 (pending)
* Added Node#remove and Node#replaceWith
<http://github.com/jhy/jsoup/issues/issue/19>

* Allow _ and - in CSS ID selectors (per CSS spec).
<http://github.com/jhy/jsoup/issues/issue/10>

Expand Down
18 changes: 18 additions & 0 deletions src/main/java/org/jsoup/nodes/Node.java
Expand Up @@ -189,6 +189,24 @@ public List<Node> childNodes() {
public Node parent() {
return parentNode;
}

/**
* Remove (delete) this node from the DOM tree. If this node has children, they are also removed.
*/
public void remove() {
Validate.notNull(parentNode);
parentNode.removeChild(this);
}

/**
* Replace this node in the DOM with the supplied node.
* @param in the node that will will replace the existing node.
*/
public void replaceWith(Node in) {
Validate.notNull(in);
Validate.notNull(parentNode);
parentNode.replaceChild(this, in);
}

protected void setParentNode(Node parentNode) {
if (this.parentNode != null)
Expand Down
18 changes: 18 additions & 0 deletions src/test/java/org/jsoup/nodes/NodeTest.java
Expand Up @@ -37,4 +37,22 @@ public class NodeTest {
assertEquals("http://jsoup.org/foo", a.attr("abs:href"));
assertFalse(a.hasAttr("abs:href")); // only realised on the get method, not in has or iterator
}

@Test public void testRemove() {
Document doc = Jsoup.parse("<p>One <span>two</span> three</p>");
Element p = doc.select("p").first();
p.childNode(0).remove();

assertEquals("two three", p.text());
assertEquals("<span>two</span> three", p.html());
}

@Test public void testReplace() {
Document doc = Jsoup.parse("<p>One <span>two</span> three</p>");
Element p = doc.select("p").first();
Element insert = doc.createElement("em").text("foo");
p.childNode(1).replaceWith(insert);

assertEquals("One <em>foo</em> three", p.html());
}
}

0 comments on commit 982e4f9

Please sign in to comment.