Select HTML Elements with the Aspose.HTML DOM API
Aspose.HTML for Java
exposes CSS selector queries through the same DOM used to load, inspect, edit, save, render, and convert an HTML document. Call
querySelector()
for the first matching Element, or
querySelectorAll()
for every match in a NodeList.
Choose CSS selectors when the target can be described naturally by an element name, ID, class, attribute, or parent-child relationship. The selected nodes remain part of the loaded HTMLDocument, allowing Java code to extract values or continue into an editing or conversion workflow without browser automation.
Select HTML Elements by Class in Java
This example loads input.html, selects every element whose class list contains product-name, and prints non-empty text from each match. Use this pattern when an application needs values from several similarly marked elements.
Read Text from Matching HTML Elements
try (HTMLDocument document = new HTMLDocument("input.html")) {
NodeList productNames = document.querySelectorAll(".product-name");
productNames.forEach(node -> {
String text = node.getTextContent().trim();
if (!text.isEmpty()) {
System.out.println(text);
}
});
}
Steps to Find HTML Elements with CSS Selectors
- Load the HTML document
into
HTMLDocument. - Describe the target elements with a class, ID, attribute, element name, or relationship selector.
- Call
querySelector()for one match orquerySelectorAll()for every match. - Check the result before reading text or attributes from the selected nodes.
- Extract the required values, edit the selected elements , or pass the document to a conversion workflow.
If a complex selector returns no matches, test a broader element, class, or ID selector first. Add attribute and relationship conditions one at a time while comparing them with the actual DOM rather than only the original source string.
When to Use CSS Selectors for HTML Processing
CSS selectors are a good fit when Java code needs to work with familiar HTML patterns:
- Select a known element. Use an ID or a specific element-and-class combination when one primary node is expected.
- Process repeated content. Select product names, navigation links, table rows, cards, or other elements marked by a shared class or attribute.
- Limit a query to a document region. Express descendant or direct-child relationships when unrelated elements appear elsewhere in the page.
- Continue with the same DOM. Read values from the returned nodes, update them through DOM methods, save the HTML, or convert the document without loading it again.
Use the simplest selector that represents the target. Detailed syntax patterns, compound selectors, positional selectors, and troubleshooting belong in the linked CSS selector documentation.
Choose Between querySelector() and querySelectorAll()
Use
querySelector()when only the first match is needed. It returns anElementornull, so check the result before reading or changing it.Use
querySelectorAll()when every match must be processed. It returns aNodeList; an unmatched selector produces a list with no matching nodes rather than a singlenullvalue.Treat selection and modification as separate operations. Selector methods locate nodes but do not change them. Calls such as
setTextContent()andsetAttribute()update the in-memory DOM, whileHTMLDocument.save()writes those changes to an HTML output.
Standard CSS selectors do not provide a general text-content condition. Use an XPath query when the selection must depend on text, ancestors, or another structural condition that CSS does not express directly.
CSS Selector Documentation for Java
- See Use CSS Selectors in Java for selector syntax, compound conditions, positional patterns, file-based examples, and troubleshooting.
- HTML Navigation places selectors alongside DOM traversal and XPath.
- The
querySelector()documents the first-match method, andquerySelectorAll()documents the multi-match result.
CSS Selectors in Java FAQ
1. How do I select an HTML element by ID or class in Java?
Pass #elementId or .className to document.querySelector() for the first match. Use querySelectorAll() when every element with the class must be processed.
2. Should Java use querySelector() or querySelectorAll() for HTML?
Use querySelector() when the workflow needs only the first matching element. Use querySelectorAll() to process every match, such as all links, rows, cards, or elements sharing a class.
3. Can CSS selectors find HTML elements by text content in Java?
Standard CSS selectors do not provide a general text-content condition. Select candidate elements and compare their getTextContent() values in Java, or use XPath when text must be part of the query.
4. What happens when a CSS selector matches no HTML elements in Java?
The querySelector() method returns null, while querySelectorAll() returns a NodeList with no matching nodes. Check the result before reading values or applying DOM changes.
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
Continue with loading, XPath, DOM editing, or extraction workflows.