Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace an element?

Tags:

java

jsoup

I have the following HTML

<html>
<head>
  <title>test</title>

</head>
<body>
  <table>
  <caption>table title and/or explanatory text</caption>
  <thead>
  <tr>
  <th>header</th>
</tr>
</thead>
<tbody>
      <tr>
      <td id=\"test\" width=\"272\"></td>
</tr>
</tbody>
</table>
<a href=\"http://www.google.fi\" style=\"color:black\">Test link</a>
<a href=\"http://www.google.fi\"><img src=\"http://www.google.se/images/nav_logo95.png\" /></a>"
</body> 
</html>;

And I want to find the first link with jsoup and replace it with a text

Element elem = page.select("a[href=" + link.getUrl() + "]:contains(" + link.getName() + ")").first();

I can only replace the inner HTML with elem.html("foo") or print the outerHtml with elem.outerHtml()

Does anyone know how I can achieve this?

like image 238
deiga Avatar asked Dec 13 '11 13:12

deiga


1 Answers

I found the answer!

TextNode text = new TextNode("foo", "");
elem.replaceWith(text);
like image 97
deiga Avatar answered Oct 21 '22 03:10

deiga