ScreenshotNeo

BlogHow-to

CSS Selectors: How to Use the select() Function

Learn how jsoup’s select() finds elements with CSS selectors in Java, how to scope and troubleshoot queries, and when browser JavaScript uses different methods.

By the ScreenshotNeo team4 October 20266 min read

In Java, select() usually refers to jsoup’s method for finding HTML elements with a CSS selector string. Parse the HTML into a Document, call select("your CSS selector"), then inspect the returned Elements. CSS itself does not define a select() function: browser JavaScript uses querySelector() or querySelectorAll() instead.

This guide focuses on jsoup, with a short browser JavaScript comparison. The examples use the documented jsoup selection APIs; check the documentation for the jsoup version in your project when relying on less common selectors. jsoup selector syntax · jsoup selection examples.

1. Add jsoup and parse HTML

Use jsoup when you need to parse or inspect HTML in Java, including HTML retrieved by your own application. The following Maven dependency uses a version placeholder; set it to the jsoup version selected for your project.

<dependency>
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  <version>YOUR_JSOUP_VERSION</version>
</dependency>

Runnable example, assuming the dependency is available on the classpath:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SelectExample {
    public static void main(String[] args) {
        String html = """
            <main id=\"main\">
              <article>
                <h2>First story</h2>
                <a class=\"story-link\" href=\"/stories/1\">Read</a>
              </article>
              <article>
                <h2>Second story</h2>
                <a class=\"story-link\" href=\"/stories/2\">Read</a>
              </article>
            </main>
            """;

        Document doc = Jsoup.parse(html);
        Elements links = doc.select("article a.story-link[href]");

        for (Element link : links) {
            System.out.println(link.text() + " -> " + link.absUrl("href"));
        }
    }
}

Jsoup.parse(String) parses the supplied HTML string. If you parse a document without a base URI, relative links may not resolve to absolute URLs; use a base URI when parsing fetched HTML if you need absUrl() values.

2. Write common CSS selectors

Pass the selector as a string. The selector describes which elements should be returned.

Selector Matches Example
p Elements by tag name All paragraphs
.notice Elements with a class Any element whose class list includes notice
#main Elements with an ID The element with ID main
a[href] Elements with an attribute Links that have an href
article p Descendants Paragraphs anywhere inside an article
h3 > div Direct children div elements directly inside an h3
img[src$=.png] Attribute suffix match Images whose src ends with .png
p.warning, p.note Selector list Paragraphs matching either branch

Selectors are not limited to these forms. For the supported syntax and version-specific details, consult jsoup’s selector syntax reference. A selector in a stylesheet, such as p { color: rebeccapurple; }, selects elements for styling; in jsoup, the selector string is an argument to a Java method.

3. Select from a Document, Element, or Elements

jsoup supports selection from a Document, an Element, or an Elements collection. Selecting from an existing element or collection scopes the search to those elements and their descendants.

Elements articles = doc.select("article");       // all matching articles
Element first = articles.first();                // first result, or null

if (first != null) {
    Elements headings = first.select("h2");     // search within this article
    System.out.println(headings.text());
}

Elements linksInArticles = articles.select("a[href]");
for (Element link : linksInArticles) {
    System.out.println(link.attr("href"));
}

Use first() only when it is valid for your task to take the first match. Check for null before using it: no matches means there is no first element. Use the full Elements result when you need every match.

4. Read and filter selected elements

After selection, use the element APIs to read text and attributes, or refine the selection with another selector.

Elements images = doc.select("img[src]");
for (Element image : images) {
    String source = image.attr("src");
    String alt = image.attr("alt");
    System.out.println(alt + " | " + source);
}

Elements pngs = doc.select("img[src$=.png]");
Elements resultDivs = doc.select("h3.r > div");
Elements resultLinks = resultDivs.select("a[href]");

The latter examples follow jsoup’s documented cookbook patterns. When a selector returns unexpected results, inspect the parsed HTML structure and verify whether the relationship should be a descendant space or a direct-child >.

5. Browser JavaScript uses querySelector methods

In a browser, use the DOM methods querySelector() and querySelectorAll() with CSS selector strings. querySelector() returns the first matching descendant (or null); querySelectorAll() returns all matching descendants in a static NodeList. Both search descendants of the node on which they are called and do not include that node itself. MDN: querySelector() · MDN: querySelectorAll().

const firstWarning = document.querySelector("p.warning");
const allWarnings = document.querySelectorAll("p.warning");

if (firstWarning) {
  console.log(firstWarning.textContent);
}

allWarnings.forEach((warning) => console.log(warning.textContent));

These browser APIs are not jsoup’s select(). Choose according to where the HTML lives: jsoup for Java parsing, browser DOM methods for a live page in JavaScript.

6. Troubleshoot selector problems

Symptom Likely cause Fix
No elements returned The parsed HTML differs from the markup you expected, or the selector is too narrow. Print or inspect the parsed document, test a broad selector such as article, then add conditions one at a time.
Only some matching elements appear The search was scoped to an Element or an Elements collection. Run the selection from the document, or confirm that the intended elements are descendants of the scope.
first() causes a null-related error The selector matched nothing, so first() returned null. Check the result before dereferencing it, and handle the no-match case.
Browser selector throws SyntaxError The selector string is invalid CSS selector syntax. Correct the selector and pass a valid selector string. MDN documents this exception for invalid selectors.
Relative URL remains relative The document was parsed without a base URI. Parse with the page’s base URL when resolving links, then use the URL-aware element method.
Direct-child query misses nested content > matches only direct children, while the markup has an intervening element. Use a descendant selector with a space if any nested descendant is intended.

Do not treat an invalid selector as equivalent to a valid selector that happens to match nothing. In browser JavaScript, an invalid selector string raises a SyntaxError; validate dynamically constructed selectors and escape values when necessary. For jsoup, check exceptions and behavior against the version in use.

7. Performance, reliability, and cost

Selection operates on the HTML tree you have parsed. Keep selectors as specific as the task requires, avoid repeating the same selection unnecessarily in tight loops, and scope searches to a relevant element when that makes the intended subtree clear. If the input comes from a remote site, network retrieval, response size, and page changes can affect the overall job independently of selector speed. Handle empty results as a normal case and keep parsing separate from assumptions about a particular page layout.

jsoup is a Java library; the cited selector documentation does not specify a universal performance benchmark or pricing model. Your costs depend on your application’s runtime and how it retrieves input. A selector cannot return content that was never present in the HTML you parsed, such as content created later by client-side JavaScript.

Or skip the browser setup

If your goal is to capture a rendered page rather than parse supplied HTML, ScreenshotNeo takes a URL and returns a screenshot or PDF. Its API supports selectors for capturing one element, and it can wait for a selector, a delay, or network idle. See the ScreenshotNeo docs.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Cookie banners, newsletter popups, and chat widgets are removed before the shot; those cleanup steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers say the page verdict and whether the shot was billed. An MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo.

Create a free account for 1,000 screenshots a month, no card required.

FAQ

Does CSS define a select() function?

No. CSS defines selector syntax. jsoup provides Java select() methods that accept selector strings; browser JavaScript provides querySelector() and querySelectorAll().

Does jsoup select() return one element?

No. It returns an Elements collection. Use first() when you want the first match, and handle the possibility that there is no match.

Can a selector find content added by page JavaScript?

Only if that content is present in the HTML tree being queried. For a live browser DOM, use browser selection methods after the content is created; for a rendered screenshot, use a browser capture service.

Can I use the same selector in jsoup and a browser?

Many common CSS selector forms overlap, but the APIs and supported syntax are not identical. Check the documentation for the environment and version you are using.