Skip to content
  • jsoup
  • News
  • Bugs
  • Discussion
  • Download
  • API Reference
  • Cookbook
  • Try jsoup
jsoup » Cookbook » Modifying data » Set the HTML of an element

Set the HTML of an element

Feb 9, 2010

Problem

You need to modify the HTML of an element.

Solution

Use the HTML setter methods in Element:

Element div = doc.select("div").first(); // <div></div>
div.html("<p>lorem ipsum</p>"); // <div><p>lorem ipsum</p></div>
div.prepend("<p>First</p>");
div.append("<p>Last</p>");
// now: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>

Element span = doc.select("span").first(); // <span>One</span>
span.wrap("<li><a href='https://example.com/'></a></li>");
// now: <li><a href="https://example.com"><span>One</span></a></li>

Discussion

  • Element.html(String html) clears any existing inner HTML in an element, and replaces it with parsed HTML.
  • Element.prepend(String first) and Element.append(String last) add HTML to the start or end of an element’s inner HTML, respectively
  • Element.wrap(String around) wraps HTML around the outer HTML of an element.

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.

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