Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
To use CSS selectors in Java, load an HTMLDocument, call
querySelector() to get the first matching element or
querySelectorAll() to get all matches, and then read or update the selected DOM nodes.
CSS selectors identify HTML elements by tag name, class, ID, attribute, position, or relationship to other elements. Aspose.HTML for Java exposes the Selectors API through the Document class, so the same selector can be used for data extraction and DOM editing.
This article demonstrates how to extract text from the first matching element, update every element that matches a compound CSS selector, and select links from an existing HTML file.
Pass a selector string directly to document.querySelector() or document.querySelectorAll(). The following patterns cover common HTML selection tasks:
| Task | CSS selector | Matches |
|---|---|---|
| Select by element name | p | Every <p> element |
| Select by class | .notice | Elements whose class list contains notice |
| Select by ID | #summary | The element with id="summary" |
| Select by attribute | [name='email'] | Elements whose name attribute equals email |
| Combine conditions as AND | p.notice[data-level='warning'] | Paragraphs that have the class and attribute |
| Select descendants | article p | Paragraphs anywhere inside an <article> |
| Select direct children | article > p | Paragraphs whose parent is an <article> |
| Combine alternatives as OR | h1, h2 | All matching <h1> and <h2> elements |
| Select by position | li:first-child | A list item that is the first child of its parent |
Do not use & as an AND operator in a selector passed to querySelector(). Combine selectors without a space, as in .notice.active, when the same element must meet both conditions. A space means a descendant relationship.
The querySelector() method returns the first Element that matches the selector. It returns null when the document contains no match.
The following Java example selects the first paragraph that is a direct child of <main> and prints its text:
HTMLDocument from the HTML string.main > p selector to querySelector().Element is null.getTextContent(). 1import com.aspose.html.HTMLDocument;
2import com.aspose.html.dom.Element;
3
4String html = "<main>"
5 + "<p>First paragraph</p>"
6 + "<section><p>Nested paragraph</p></section>"
7 + "</main>";
8
9HTMLDocument document = new HTMLDocument(html, ".");
10Element paragraph = document.querySelector("main > p");
11
12if (paragraph != null) {
13 System.out.println(paragraph.getTextContent());
14}The selector matches only the direct child of <main>, so the console output is:
First paragraph
The querySelectorAll() method returns a NodeList containing every element that matches the selector. Use it when several elements must be inspected or changed.
The next example finds list items that have both class="task" and data-status="new", applies an inline background color, and saves the updated DOM to selected-tasks.html:
HTMLDocument containing the list items.querySelectorAll() with the compound selector li.task[data-status='new'].NodeList and update each matching element.save() to write the modified HTML document. 1import com.aspose.html.HTMLDocument;
2import com.aspose.html.collections.NodeList;
3import com.aspose.html.dom.Element;
4
5String html = "<ul>"
6 + "<li class='task' data-status='new'>Review HTML</li>"
7 + "<li class='task' data-status='done'>Check links</li>"
8 + "<li class='task' data-status='new'>Update metadata</li>"
9 + "</ul>";
10
11HTMLDocument document = new HTMLDocument(html, ".");
12NodeList elements = document.querySelectorAll("li.task[data-status='new']");
13
14elements.forEach(node -> {
15 Element element = (Element) node;
16 element.setAttribute("style", "background-color: #fff3cd;");
17});
18
19document.save("selected-tasks.html");The saved HTML contains the new style attribute on the first and third list items. The item whose data-status value is done remains unchanged.
In a typical data-extraction workflow, the source is an existing HTML file rather than markup created inside the Java code. The following example loads
css-selector-resources.html, selects documentation links from published resource cards, and prints their text and href values:
HTMLDocument.data-status value is published.NodeList and read each link’s text and href attribute. 1import com.aspose.html.HTMLDocument;
2import com.aspose.html.collections.NodeList;
3import com.aspose.html.dom.Element;
4
5String inputPath = "css-selector-resources.html";
6HTMLDocument document = new HTMLDocument(inputPath);
7
8NodeList links = document.querySelectorAll(
9 "article.resource[data-status='published'] a.docs-link"
10);
11
12links.forEach(node -> {
13 Element link = (Element) node;
14 System.out.println(
15 link.getTextContent().trim() + ": " + link.getAttribute("href")
16 );
17});The selector excludes the resource card whose status is draft. The console output contains only the two published documentation links:
Read the navigation guide: https://docs.aspose.com/html/java/html-navigation/Read the editing guide: https://docs.aspose.com/html/java/edit-a-document/
| Method | Return value | Use it when |
|---|---|---|
querySelector() | The first matching Element, or null | Only one match is required |
querySelectorAll() | A NodeList containing all matches | Every matching element must be read or updated |
Neither method removes nodes from the document. Changes made to a selected element update the in-memory DOM; call HTMLDocument.save() when the changes must be written to an HTML file.
| Issue | Cause and fix |
|---|---|
querySelector() returns null | No element matches the selector. Check the loaded DOM, spelling, case-sensitive attribute values, and selector relationships. |
querySelectorAll() returns no elements | Start with a simpler selector, such as the element name or class, and then add attributes or combinators. |
.notice.active and .notice .active return different results | Without a space, both classes must belong to the same element. With a space, .active must be a descendant of .notice. |
| The updated HTML file does not change | DOM changes remain in memory until save() is called with the required output path. |
| A style change is not visible | Another CSS declaration may have greater specificity or use !important. Inspect the existing inline, internal, and external styles. |
A CSS selector is a string that describes which HTML elements to match. With Aspose.HTML for Java, pass that string to querySelector() or querySelectorAll() to locate elements in an HTMLDocument.
Use .className for a class and #elementId for an ID. For example, .notice selects elements with the notice class, while #summary selects the element whose ID is summary.
Use an attribute selector such as [name='email']. Add an element name when needed, for example input[name='email'].
For AND, combine conditions without a space, for example button.primary[disabled]. For OR, separate complete selectors with a comma, for example h1, h2, h3. The & character is not the AND operator for a selector passed to the DOM query methods.
Standard CSS selectors do not provide a general text-content selector. Select candidate elements and compare their getTextContent() values in Java, or use XPath when the query must include a text condition.
querySelector() returns null. querySelectorAll() returns a NodeList with no matching items. Check the result before reading an element or assuming that the collection contains nodes.
TreeWalker, NodeFilter, and direct DOM navigation.HTMLDocument.Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.