Set the HTML of an element

Problem

You need to modify the HTML of an element.

Solution

Use the HTML setter methods in Element:

  1. Element div = doc.select("div").first(); // <div></div>
  2. div.html("<p>lorem ipsum</p>"); // <div><p>lorem ipsum</p></div>
  3. div.prepend("<p>First</p>");
  4. div.append("<p>Last</p>");
  5. // now: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>
  6. Element span = doc.select("span").first(); // <span>One</span>
  7. span.wrap("<li><a href='http://example.com/'></a></li>");
  8. // now: <li><a href="http://example.com"><span>One</span></a></li>

Discussion

See also

You can also use the Element.prependElement(String tag) and Element.appendElement(String tag) methods to create new elements and insert them into the document flow as a child element.