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></div>
div.text("five > four"); // <div>five > four</div>
div.prepend("First ");
div.append(" Last");
// now: <div>First five > four Last</div>
Discussion
The text setter methods mirror the HTML setter methods:
Element.text(
clears any existing inner HTML in an element, and replaces it with the supplied text.String text) Element.prepend(
andString first) Element.append(
add text nodes to the start or end of an element's inner HTML, respectivelyString last)
The text should be supplied unencoded: characters like <
, >
etc will be treated as literals, not HTML.
Cookbook
Introduction
Input
- Parse a document from a String
- Parsing a body fragment
- Load a Document from a URL
- Load a Document from a File
- Parse large documents efficiently with StreamParser
Extracting data
- Use DOM methods to navigate a document
- Use CSS selectors to find elements
- Use XPath selectors to find elements and nodes
- Extract attributes, text, and HTML from elements
- Working with relative and absolute URLs
- Example program: list links
Modifying data
- Set attribute values
- Set the HTML of an element
- Setting the text content of elements