13.Setting the text content of elements

来源:百度文库 编辑:神马文学网 时间:2024/04/28 11:37:25

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:

Element div = doc.select("div").first(); // 
 
div.text("five > four"); //
five > four
 
div.prepend("First ");div.append(" Last"); 
// now:
First five > four Last

Discussion

The text setter methods mirror the HTML setter methods:

  • Element.text(String text) clears any existing inner HTML in an element, and replaces it with the supplied text.
  • Element.prepend(String first) and Element.append(String last) add text nodes to the start or end of an element's inner HTML, respectively

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