Modify HTML with a Java DOM API

Aspose.HTML for Java represents an HTML document as a DOM tree. Load or create an HTMLDocument , locate the required elements, and update the tree through standard DOM-style methods. The same in-memory document can then be saved as HTML or passed to a renderer or converter.

DOM editing is appropriate when changes must preserve document structure instead of treating HTML as undifferentiated text. Elements can be created, inserted, moved, replaced, or removed; text and attributes can be read or updated independently.


Select, Add, Replace, and Remove HTML Elements

The example starts with a small HTML document, changes the heading, appends a note, replaces the status paragraph, removes an obsolete element, and saves the final DOM to edited.html.

Edit an HTML Document in Java

String html = "<main>"
        + "<h1 id='title'>Draft report</h1>"
        + "<p id='status'>Pending review</p>"
        + "<p class='obsolete'>Temporary note</p>"
        + "</main>";

try (HTMLDocument document = new HTMLDocument(html, ".")) {
    Element main = document.querySelector("main");

    // Update text and an attribute
    Element heading = document.querySelector("#title");
    heading.setTextContent("Quarterly report");
    heading.setAttribute("class", "report-title");

    // Create and append a new element
    Element note = document.createElement("p");
    note.setAttribute("class", "summary");
    note.setTextContent("Prepared for publication");
    main.appendChild(note);

    // Replace an existing element
    Element oldStatus = document.querySelector("#status");
    Element newStatus = document.createElement("p");
    newStatus.setAttribute("id", "status");
    newStatus.setTextContent("Published");
    main.replaceChild(newStatus, oldStatus);

    // Remove an obsolete element
    Element obsolete = document.querySelector(".obsolete");
    main.removeChild(obsolete);

    document.save("edited.html");
}

Steps to Edit an HTML File in Java

  1. Load the HTML source into an HTMLDocument.
  2. Find the target element with an ID lookup, a CSS selector , or an XPath query .
  3. Create new elements or text nodes when the document structure must change.
  4. Update text, attributes, classes, links, or CSS with the appropriate DOM methods.
  5. Append, insert, replace, or remove nodes through their parent element.
  6. Save the modified DOM as HTML or convert the document to the required output format.

Keep related changes in one document lifetime. This makes the final save operation represent a coherent DOM state and avoids repeatedly parsing the same source.


DOM Methods for Editing HTML

Choose the operation according to the intended change:

Check selector results before editing when a source document may not contain the expected element. A missing result from querySelector() is null; attempting to call a method on it produces a Java error before the DOM can be changed.


Plain Text, HTML Fragments, Attributes, and CSS

  1. Use setTextContent() or createTextNode() when a value must remain plain text. Characters that look like HTML remain textual content rather than becoming elements. Use setInnerHTML() only for an HTML fragment created by the application or sanitized before being parsed into descendant nodes. It replaces the current children of the target element, so it is not the right operation when existing children must be preserved.

  2. Use setAttribute() for identifiers, classes, links, data attributes, accessibility attributes, and inline styles. For one element, the style attribute can hold CSS declarations. For reusable rules, create a <style> element, set its text, and append it to the document <head>.

  3. DOM changes affect the in-memory HTMLDocument. They do not update the original file automatically. Call save() with the required output path after editing. Use a conversion API instead when the required result is PDF, XPS, DOCX, or an image rather than HTML.


HTML Editing Documentation for Java


Editing HTML in Java FAQ

1. How do I change text inside an HTML element in Java?

Locate the element and call setTextContent(newText). The value is stored as text and is not parsed as an HTML fragment. Save the document after all required changes are complete.

2. What is the difference between setTextContent() and setInnerHTML()?

The setTextContent() method treats the supplied value as plain text and replaces descendant content. The setInnerHTML() method parses HTML markup and replaces the element’s existing children with the resulting nodes.

3. How do I add or remove an HTML element through the DOM?

Create an element with document.createElement(), configure it, and add it with appendChild() or insertBefore(). To remove a node, call removeChild() on its parent.

4. Does editing HTMLDocument change the original HTML file?

No. Edits change the in-memory DOM. Call document.save(outputPath) to write an HTML result, or use a conversion workflow to produce another format.


Install Aspose.HTML for Java

Add Aspose.HTML for Java from the official Aspose repository. Replace ASPOSE_HTML_VERSION with an exact version from the Aspose.HTML for Java releases page, then reload or rebuild the project so the dependency is resolved.

Add the repository and dependency to the Maven project:

Maven – pom.xml

<repositories>
    <repository>
        <id>AsposeJavaAPI</id>
        <url>https://releases.aspose.com/java/repo/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>com.aspose</groupId>
        <artifactId>aspose-html</artifactId>
        <version>ASPOSE_HTML_VERSION</version>
    </dependency>
</dependencies>

Add the repository and dependency to the Gradle project:

Gradle – build.gradle

repositories {
    maven {
        url = uri('https://releases.aspose.com/java/repo/')
    }
}
dependencies {
    implementation 'com.aspose:aspose-html:ASPOSE_HTML_VERSION'
}

Use a JDK compatible with the selected release. For manual JAR installation, Kotlin DSL, updates, and dependency troubleshooting, see Install Aspose.HTML for Java .

Related Java HTML Parser Guides

Load a document, choose a query method, or continue to extraction and conversion.