Setting the text content of elements

Problem

You need to modify the text content of a HTML document.

Solution

Use the text setter methods of Element:

  1. Element div = doc.select("div").first(); // <div></div>
  2. div.text("five > four"); // <div>five &gt; four</div>
  3. div.prepend("First ");
  4. div.append(" Last");
  5. // now: <div>First five &gt; four Last</div>

Discussion

The text setter methods mirror the HTML setter methods:

The text should be supplied unencoded: characters like <, > etc will be treated as literals, not HTML.