Assume I have the following html:
<html>
<head>
</head>
<body>
<div id="wrapper" >
<div class="s2">I am going <a title="some title" href="">by flying</a>
<p>mr tt</p>
</div>
</div>
</body>
</html>
Any words in the text nodes that are equal to or greater than 4 characters for example the word ‘going’ is replaced with html content (not text) <span>going<span> in the original html without changing anything else.
If I try do something like element.html(replacement), the problem is if lets the current element is <div class="s2"> it will also wipe off <a title="some title"
In this case you must traverse your document as suggested by this answer. Here’s a way of doing it using Jsoup APIs:
NodeTraversorandNodeVisitorallow you to traverse the DOMNode.replaceWith(...)allows for replacing a node in the DOMHere’s the code: