# Creating Effective Selectors for AssertionHub

> Learn how to create reliable CSS selectors that work seamlessly with AssertionHub's automated testing engine for accurate element targeting.

Source: https://assertionhub.com/docs/creating-selectors-assertionhub
Published: 2025-07-31 · Updated: 2026-11-28

# AssertionHub Selector Reference

Selectors tell AssertionHub exactly which elements to interact with on your website. They work like CSS selectors but with additional features for automation reliability.

## How to Test and Create Selectors

**Always test your selectors before using them in AssertionHub.** Follow this step-by-step approach:

### Step 1: Open Browser Developer Tools

1. Navigate to your target webpage
2. Right-click and select "Inspect" or press `F12`
3. Use the element inspector (cursor icon top left of the devtools panel just opened) to hover over your target element
4. Choose a selector based on the HTML you see. Below the list of all supported selectors

### Step 2: Test Your Selector in Console

1. Switch to the "Console" tab in developer tools
2. Test your selector with `querySelector()`:

```javascript
document.querySelector("your-selector-here");
```

**If it returns `null`:** Your selector doesn't match any element - refine it.

### Step 3: Check for Multiple Matches

Use `querySelectorAll()` to see how many elements match:

```javascript
document.querySelectorAll("your-selector-here");
```

**If it returns multiple elements:**

- Add more specificity (parent containers, additional attributes)
- Or use positional selectors (`.first()`, `.nth(2)`, etc.)

**If it returns exactly 1 element:** Perfect! Your selector is ready.

### Step 4: Refine as Needed

- **Too many matches:** Add parent context like `.container button` instead of just `button`
- **No matches:** Start broader and add specificity gradually
- **Wrong element:** Use more specific attributes or text content

**Example workflow:**

```javascript
// Start broad
document.querySelectorAll("button"); // Returns 15 buttons

// Add specificity
document.querySelectorAll(".checkout-section button"); // Returns 3 buttons

// Add more specificity
document.querySelectorAll(".checkout-section button:has-text('Submit')"); // Returns 1 button ✓
```

---

## Selector Types Reference

### Element Selectors

Target elements by their HTML tag type:

```css
button   /* Any button element */
input    /* Any input field */
div      /* Any div element */
form     /* Any form element */
a        /* Any link */
img      /* Any image */
span     /* Any span element */
h1       /* Any h1 heading */
p        /* Any paragraph */
select   /* Any dropdown */
textarea /* Any textarea */
```

### Class Selectors

Target elements by their CSS class names (prefix with `.`):

```css
.btn-primary        /* Element with class "btn-primary" */
.modal-content      /* Element with class "modal-content" */
.checkout-form      /* Element with class "checkout-form" */
.product-card       /* Element with class "product-card" */
.navigation-menu    /* Element with class "navigation-menu" */
```

### ID Selectors

Target elements by their unique ID (prefix with `#`):

```css
#submit-button      /* Element with id="submit-button" */
#email-input        /* Element with id="email-input" */
#cart-total         /* Element with id="cart-total" */
#navigation-menu    /* Element with id="navigation-menu" */
#main-content       /* Element with id="main-content" */
```

### Attribute Selectors

Target elements by their HTML attributes. Can be used standalone or with element types:

**Standalone attribute selectors:**

```css
[data-testid="add-to-cart"]           /* Any element with this data-testid */
[type="email"]                        /* Any element with type="email" */
[type="password"]                     /* Any element with type="password" */
[type="checkbox"]                     /* Any checkbox */
[type="radio"]                        /* Any radio button */
[name="username"]                     /* Any element with name="username" */
[placeholder="Enter your email"]      /* Any element with this placeholder */
[aria-label="Close dialog"]          /* Any element with this aria-label */
[role="button"]                       /* Any element with role="button" */
[role="dialog"]                       /* Any dialog element */
[value="submit"]                      /* Any element with value="submit" */
[href="/contact"]                     /* Any element with href="/contact" */
```

**Combined with element types:**

```css
button[data-testid="submit"]          /* Button with specific data-testid */
input[type="email"]                   /* Input with type="email" */
a[href*="product"]                    /* Link with href containing "product" */
div[class*="modal"]                   /* Div with class containing "modal" */
```

**Partial attribute matching:**

```css
[src*="image"]                        /* Element with src containing "image" */
[class*="btn"]                        /* Element with class containing "btn" */
[href*="checkout"]                    /* Element with href containing "checkout" */
[data-testid*="product"]              /* Element with data-testid containing "product" */
```

### Text-Based Selectors

Target elements by their visible text content:

```css
button:has-text("Add to Cart")        /* Button containing "Add to Cart" */
a:has-text("Contact Us")              /* Link containing "Contact Us" */
span:has-text("$29.99")               /* Span containing "$29.99" */
div:has-text("Out of Stock")          /* Div containing "Out of Stock" */
h1:has-text("Welcome")                /* H1 containing "Welcome" */
```

### Alternative Text Selectors

```css
[text="Add to Cart"]                  /* Element with exact text "Add to Cart" */
[text*="Cart"]                        /* Element with text containing "Cart" */
```

### Combined Selectors

Mix selector types for more precision:

```css
button.btn-primary                              /* Button with class "btn-primary" */
form input[type="email"]                        /* Email input inside a form */
.modal .close-button                            /* Element with class "close-button" inside modal */
button[class*="primary"]:has-text("Submit")     /* Button with "primary" in class and "Submit" text */
div[data-testid="product-card"]:has-text("iPhone")  /* Product card containing "iPhone" */
.checkout-form input[name="email"]              /* Email input inside checkout form */
```

## Positional Selectors

When multiple elements match your selector, specify which one to target with this syntax: `.method()`

### First Element

```
button:has-text("Add to Cart").first() /* First "Add to Cart" button */
div.product-card.first(); /* First product card */
```

### Last Element

```css
.navigation-link.last()                   /* Last navigation link */
.breadcrumb-item.last()                   /* Last breadcrumb item */
```

### Nth Element (zero-indexed)

```css
.product-card.nth(0)        /* First product card (index 0) */
.product-card.nth(1)        /* Second product card (index 1) */
.product-card.nth(2)        /* Third product card (index 2) */
form input.nth(0)           /* First input in form */
```

**Note:** Counting starts at 0, so `.nth(0)` = first element, `.nth(1)` = second element.

## Iframe Selectors

For elements inside iframes (payment forms, embedded widgets), use the `>>` operator:

```css
iframe[src*="payment-gateway"] >> input[name="card-number"]
iframe[title="Secure Payment Form"] >> button:has-text("Pay Now")
iframe[class*="embed"] >> .widget-content
iframe[id="payment-frame"] >> input[name="cvv"]
iframe >> button:has-text("Submit")               /* Any iframe with Submit button */
```

**Syntax:** `iframe-selector >> element-inside-iframe`

- Left side: selector for the iframe container
- Right side: selector for element inside the iframe
- AssertionHub automatically waits for iframe to load

## Parent-Child Relationships

Target elements within specific containers by separating selectors with spaces:

```css
.shopping-cart button:has-text("Remove")    /* "Remove" button inside shopping cart */
.product-details .price-section             /* Price section inside product details */
.modal-content .close-button                /* Close button inside modal content */
form.checkout input[type="email"]           /* Email input inside checkout form */
nav .dropdown-menu a                        /* Links inside dropdown menu in nav */
```

## Multiple Attribute Selectors

Combine multiple attributes for precise targeting:

```css
button[class*="primary"]:has-text("Continue")             /* Button with "primary" class and "Continue" text */
input[type="email"][placeholder= "Enter your email"]      /* Email input with specific placeholder */
div[data-testid="product-card"][data-product-id= "123"]   /* Product card with specific ID */
a[href * = "product"][class * = "link"];                /* Link with "product" in href and "link" in class */
```

## Common Usage Patterns

### E-commerce Actions

```css
[data-product-id="12345"] button:has-text("Add to Cart")   /* Add specific product to cart */
.product-card.nth(0) .add-to-cart-button                  /* Add first product to cart */
.size-selector input[value="Medium"]                      /* Select medium size */
.cart-item button:has-text("Remove")                      /* Remove item from cart */
.checkout-form input[name="email"]                        /* Email field in checkout */
button:has-text("Place Order")                            /* Complete purchase */
```

### Form Interactions

```css
input[placeholder="Enter your email"]        /* Email input field */
input[type="password"]                       /* Password field */
textarea[name="message"]                     /* Message textarea */
select[name="country"]                       /* Country dropdown */
input[type="checkbox"][name="newsletter"]    /* Newsletter checkbox */
form[id="contact-form"] button[type="submit"] /* Submit contact form */
```

### Navigation Elements

```css
nav a:has-text("Products")                   /* Products menu link */
.main-menu .dropdown-toggle                 /* Dropdown menu trigger */
.breadcrumb a:has-text("Home")              /* Home breadcrumb link */
[role="dialog"] button:has-text("Close")    /* Close modal dialog */
.modal-content .confirm-button              /* Confirm button in modal */
```

## Hover-Dependent Elements

Some elements only appear after hovering over another element (dropdown menus, tooltips). Configure these in two steps:

1. **Hover target:** Element to hover over (e.g., `.main-nav a:has-text("Products")`)
2. **Click target:** Element that appears (e.g., `.dropdown-menu a:has-text("Smartphones")`)

Set the hover target in your test step configuration, then specify the click target as your main selector.

## Selector Reliability

### Recommended (Stable)

```css
[data-testid="element"]     /* Data attributes created for testing */
#unique-id                  /* Unique IDs */
[aria-label="description"]  /* Accessibility labels */
button:has-text("Text")     /* Visible text content */
input[type="email"]         /* Semantic form attributes */
```

### Avoid (Unstable)

```css
.css-1a2b3c4                /* Auto-generated CSS classes */
div:nth-child(7)            /* Position-dependent selectors */
div > div > span            /* Overly generic nested selectors */
```

## Good to know

- When several elements match and you don't add `.first()`, `.last()` or `.nth()`, the first one is used.
- AssertionHub waits for the element to appear and scrolls to it before acting, so you don't need extra steps for that.

### Entering Selectors

1. Open the step (in the recorder or in **Quick edit**).
2. Type the selector under **Selectors**, or click **Pick from page** in the recorder and click the element.
3. **Test a typed selector first** with the developer tools method above.

Can't find a stable selector? Describe the element in the step's description (for example "the Add to cart button") and turn on **AI fallback**: AssertionHub uses the description when the selectors stop working.

## Troubleshooting Common Issues

### Element Not Found

- **Test in console:** Use `document.querySelector("selector")` - if it returns `null`, the selector is wrong
- **Check timing:** Element might not exist when action runs
- **Check iframe:** Element might be inside an iframe requiring `>>` syntax. Unfortunately this cannot be tested with querySelector.

### Multiple Elements Found

- **Test in console:** Use `document.querySelectorAll("selector")` to see how many match
- **Add parent context:** `.container .button` instead of just `.button`
- **Use positional methods:** `.selector.first()` or `.selector.nth(0)`
- **Combine attributes:** Add more specificity with multiple attributes

### Iframe Issues

- **Check iframe loading:** Ensure iframe loads completely before targeting internal elements
- **Verify iframe selector:** Test left side of `>>` with `document.querySelector("iframe-selector")`
- **Test internal element:** Switch to iframe context in dev tools to test right side of `>>`

**Remember:** Always use `document.querySelector()` and `document.querySelectorAll()` in browser console to test selectors before implementing them in AssertionHub.
