Skip to content
  • jsoup
  • News
  • Bugs
  • Discussion
  • Download
  • API Reference
  • Cookbook
  • Try jsoup
jsoup » Cookbook » Modifying data » Setting the text content of elements

Setting the text content of elements

Feb 9, 2010

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 &gt; four</div>
div.prepend("First ");
div.append(" Last");
// now: <div>First five &gt; four Last</div>

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.

Cookbook

Introduction

  1. Parsing and traversing a Document

Input

  1. Parse a document from a String
  2. Parsing a body fragment
  3. Load a Document from a URL
  4. Load a Document from a File
  5. Parse large documents efficiently with StreamParser

Extracting data

  1. Use DOM methods to navigate a document
  2. Use CSS selectors to find elements
  3. Use XPath selectors to find elements and nodes
  4. Extract attributes, text, and HTML from elements
  5. Working with relative and absolute URLs
  6. Example program: list links

Modifying data

  1. Set attribute values
  2. Set the HTML of an element
  3. Setting the text content of elements

Cleaning HTML

  1. Sanitize untrusted HTML (to prevent XSS)

Working with the web

  1. Maintaining a request session
jsoup HTML parser © 2009 - 2026 Jonathan Hedley