Use CSS Selectors in Java – querySelector and querySelectorAll

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.

CSS Selector Syntax in Java

Pass a selector string directly to document.querySelector() or document.querySelectorAll(). The following patterns cover common HTML selection tasks:

TaskCSS selectorMatches
Select by element namepEvery <p> element
Select by class.noticeElements whose class list contains notice
Select by ID#summaryThe element with id="summary"
Select by attribute[name='email']Elements whose name attribute equals email
Combine conditions as ANDp.notice[data-level='warning']Paragraphs that have the class and attribute
Select descendantsarticle pParagraphs anywhere inside an <article>
Select direct childrenarticle > pParagraphs whose parent is an <article>
Combine alternatives as ORh1, h2All matching <h1> and <h2> elements
Select by positionli:first-childA 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.

Find the First Matching Element with querySelector()

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:

  1. Create an HTMLDocument from the HTML string.
  2. Pass the main > p selector to querySelector().
  3. Check whether the returned Element is null.
  4. Read the element text with 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

Select and Update Elements with querySelectorAll()

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:

  1. Create an HTMLDocument containing the list items.
  2. Call querySelectorAll() with the compound selector li.task[data-status='new'].
  3. Iterate through the returned NodeList and update each matching element.
  4. Call 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.

Use CSS Selectors with an HTML File

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:

  1. Download the sample HTML file to the application’s working directory.
  2. Load the file into an HTMLDocument.
  3. Select links inside resource cards whose data-status value is published.
  4. Iterate through the returned 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/

querySelector() vs. querySelectorAll()

MethodReturn valueUse it when
querySelector()The first matching Element, or nullOnly one match is required
querySelectorAll()A NodeList containing all matchesEvery 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.

Common CSS Selector Issues

IssueCause and fix
querySelector() returns nullNo element matches the selector. Check the loaded DOM, spelling, case-sensitive attribute values, and selector relationships.
querySelectorAll() returns no elementsStart with a simpler selector, such as the element name or class, and then add attributes or combinators.
.notice.active and .notice .active return different resultsWithout 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 changeDOM changes remain in memory until save() is called with the required output path.
A style change is not visibleAnother CSS declaration may have greater specificity or use !important. Inspect the existing inline, internal, and external styles.

FAQ

What is a CSS selector in Java HTML processing?

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.

How do I select an HTML element by class or ID?

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.

How do I select an element by its name attribute?

Use an attribute selector such as [name='email']. Add an element name when needed, for example input[name='email'].

How do I write AND and OR conditions in a CSS selector?

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.

Can a CSS selector find an element by its text content?

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.

What happens when a CSS selector matches nothing?

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.

Related Articles