CSS Attribute Selectors

Matching Attributes

SelectorMeaningExample
[attr='v']equalsinput[name='email']
[attr*='v']containsa[href*='/products/']
[attr^='v']starts withbutton[data-testid^='add-']
[attr$='v']ends withimg[src$='.png']

Example

// every "Add to Cart" button on the search page, whatever the product id
List<WebElement> addButtons = driver.findElements(By.cssSelector("button[data-testid^='add-']"));
System.out.println("Add buttons: " + addButtons.size());

Example

Output:

Run AttributeTest.main()

Example output

Add buttons: 24

Note: CSS cannot match by visible text. For "the button that says Add to Cart" use XPath.

How Attribute Matching Works

Example

This runnable example applies the same four rules to attribute values with plain Java string methods:

public class Main {
    static boolean matches(String op, String actual, String wanted) {
        return switch (op) {
            case "="  -> actual.equals(wanted);
            case "*=" -> actual.contains(wanted);
            case "^=" -> actual.startsWith(wanted);
            case "$=" -> actual.endsWith(wanted);
            default -> throw new IllegalArgumentException(op);
        };
    }

    public static void main(String[] args) {
        String[] testIds = {"add-101", "add-102", "wishlist-101", "cart-count"};
        for (String op : new String[] {"^=", "*=", "$="}) {
            String wanted = op.equals("$=") ? "101" : op.equals("^=") ? "add-" : "list";
            StringBuilder hits = new StringBuilder();
            for (String id : testIds) if (matches(op, id, wanted)) hits.append(id).append(' ');
            System.out.println("[data-testid" + op + "'" + wanted + "'] -> " + hits.toString().trim());
        }
    }
}

Output

[data-testid^='add-'] -> add-101 add-102
[data-testid*='list'] -> wishlist-101
[data-testid$='101'] -> add-101 wishlist-101