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
- Load the HTML source
into an
HTMLDocument. - Find the target element with an ID lookup, a CSS selector , or an XPath query .
- Create new elements or text nodes when the document structure must change.
- Update text, attributes, classes, links, or CSS with the appropriate DOM methods.
- Append, insert, replace, or remove nodes through their parent element.
- 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:
querySelector()orgetElementById()locates an existing element.createElement()creates an element owned by the document.createTextNode()creates text without interpreting HTML tags inside the value.appendChild()adds a node as the last child and moves an existing node when it already belongs elsewhere in the document.insertBefore()inserts a node before a known child when position matters.replaceChild()substitutes one child node for another.removeChild()removes a child from its parent.setAttribute()adds an attribute or replaces its current value.setTextContent()replaces an element’s descendant content with plain text.
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
Use
setTextContent()orcreateTextNode()when a value must remain plain text. Characters that look like HTML remain textual content rather than becoming elements. UsesetInnerHTML()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.Use
setAttribute()for identifiers, classes, links, data attributes, accessibility attributes, and inline styles. For one element, thestyleattribute can hold CSS declarations. For reusable rules, create a<style>element, set its text, and append it to the document<head>.DOM changes affect the in-memory
HTMLDocument. They do not update the original file automatically. Callsave()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
- See
Edit HTML Documents in Java
for DOM tree operations,
innerHTML,outerHTML, attributes, and CSS examples. - Save HTML Documents in Java explains HTML output and related-resource handling.
- The
DocumentAPI Reference covers node creation and queries. Use theElementandNodereferences for attributes, content, insertion, replacement, and removal operations.
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.