### Install unique-selector Package Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Install the unique-selector package using npm. This command adds the package to your project's dependencies. ```bash npm install @cypress/unique-selector ``` -------------------------------- ### Basic usage of unique-selector library Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Import the unique function and use it to get a unique CSS selector for a given DOM element. The selector returned will be one of the preferred types or a fallback. ```javascript import unique from '@cypress/unique-selector'; // Get a unique selector for an element const element = document.querySelector('.my-button'); const selector = unique(element); // Returns: '#my-button' or '.my-button' or 'button' etc. ``` -------------------------------- ### Generate Unique CSS Selector for a DOM Element Source: https://context7.com/cypress-io/unique-selector/llms.txt Use the `unique` function to get a CSS selector for a given DOM element. Returns `null` for detached elements. ```javascript import unique from '@cypress/unique-selector'; // --- Basic usage --- const btn = document.querySelector('#submit'); console.log(unique(btn)); // → '#submit' // --- Element with only classes --- const card = document.querySelector('.product-card'); console.log(unique(card)); // → '.product-card' (if unique in document) // → 'body > :nth-child(3)' (fallback if class is not unique) // --- Default selectorTypes order: ['id', 'name', 'class', 'tag', 'nth-child'] --- const input = document.querySelector('[name="email"]'); console.log(unique(input)); // → '[name="email"]' // --- Null for detached element --- const detached = document.createElement('div'); console.log(unique(detached)); // → null ``` -------------------------------- ### Performance Caching with options.selectorCache / options.isUniqueCache Source: https://context7.com/cypress-io/unique-selector/llms.txt Utilize `selectorCache` and `isUniqueCache` (both `Map` instances) for performance optimization on repeated calls. `selectorCache` maps elements to their selector segments, while `isUniqueCache` maps full selectors to a boolean indicating uniqueness. The caller is responsible for invalidating these caches when the DOM changes. ```javascript import unique from '@cypress/unique-selector'; const selectorCache = new Map(); const isUniqueCache = new Map(); const options = { selectorCache, isUniqueCache }; // First call — populates both caches const s1 = unique(document.querySelector('#header'), options); console.log(s1); // → '#header' // Subsequent calls for sibling elements reuse cached segment for shared ancestors const s2 = unique(document.querySelector('#footer'), options); console.log(s2); // → '#footer' // Invalidate when DOM is mutated document.body.innerHTML = ''; selectorCache.clear(); isUniqueCache.clear(); ``` -------------------------------- ### unique(element, options?) Source: https://context7.com/cypress-io/unique-selector/llms.txt Generates the shortest possible CSS selector that uniquely identifies a DOM element within its root node. It walks up the DOM tree, building a child-combinator selector chain, and stops at the shortest prefix that uniquely identifies the element. Returns a CSS selector string, or null if the element has no parent node. ```APIDOC ## unique(element, options?) ### Description Generate a unique CSS selector for a DOM element. ### Method `unique(element, options?)` ### Parameters #### Path Parameters - **element** (DOM Element) - The DOM element for which to generate a selector. - **options** (Object) - Optional. Configuration options for selector generation. - **selectorTypes** (Array) - An array of strings specifying the ordered set of strategies the library will attempt. Built-in strategies include 'id', 'name', 'class', 'tag', 'nth-child', and 'attributes'. Custom strategies like 'data-*' or 'attribute:' are also supported. - **attributesToIgnore** (Array) - An array of attribute names that the 'attributes' selector strategy will skip. Defaults to ['id', 'class', 'length']. ### Request Example ```javascript import unique from '@cypress/unique-selector'; const btn = document.querySelector('#submit'); console.log(unique(btn)); const el = document.querySelector('[data-cy="login-btn"]'); console.log(unique(el, { selectorTypes: ['data-cy', 'nth-child'] })); ``` ### Response #### Success Response (200) - **selector** (string) - A CSS selector string that uniquely identifies the element, or null if the element has no parent node. ``` -------------------------------- ### options.selectorTypes Source: https://context7.com/cypress-io/unique-selector/llms.txt Control which selector strategies are tried and in what order. This option allows customization of the selector generation process by specifying an ordered list of selector types to attempt. ```APIDOC ## options.selectorTypes ### Description Control which selector strategies are tried and in what order. ### Details An array of strings specifying the ordered set of strategies the library will attempt. Built-in strategies are 'id', 'name', 'class', 'tag', 'nth-child', and 'attributes' (all non-ignored attributes). Additionally, any `data-*` string (e.g. `'data-testid'`) targets that specific data attribute, and `'attribute:'` (e.g. `'attribute:role'`) targets any named attribute. ### Request Example ```javascript import unique from '@cypress/unique-selector'; const el = document.querySelector('[data-cy="login-btn"]'); console.log(unique(el, { selectorTypes: ['data-cy', 'nth-child'] })); const modal = document.querySelector('[role="dialog"]'); console.log(unique(modal, { selectorTypes: ['attribute:role', 'class', 'nth-child'] })); ``` ``` -------------------------------- ### Shadow DOM Support in Unique Selector Source: https://context7.com/cypress-io/unique-selector/llms.txt Demonstrates how unique selector scopes its checks within a ShadowRoot when an element is inside a Shadow DOM tree. It automatically prefixes with `:host >` when necessary. ```javascript import unique from '@cypress/unique-selector'; const host = document.querySelector('#shadow-host'); const shadowRoot = host.attachShadow({ mode: 'open' }); shadowRoot.innerHTML = '
'; // Selector for the shadow host — scoped to the document console.log(unique(host)); // → '#shadow-host' // Selector for shadow content — scoped to the ShadowRoot const btn = shadowRoot.querySelector('button'); console.log(unique(btn)); // → '#inner > :nth-child(1)' // When a top-level shadow element's nth-child collides with nested children, // the library prefixes with :host > shadowRoot.innerHTML = '
'; const topBtn = shadowRoot.querySelector('button'); console.log(unique(topBtn, { selectorTypes: ['nth-child'] })); // → ':host > :nth-child(1)' ``` -------------------------------- ### Control Selector Strategies with options.selectorTypes Source: https://context7.com/cypress-io/unique-selector/llms.txt Customize the order and types of selectors generated by passing an array to `selectorTypes`. This allows prioritizing specific attributes like `data-cy` or `role`. ```javascript import unique from '@cypress/unique-selector'; const el = document.querySelector('[data-cy="login-btn"]'); // Use only data-cy, fall back to nth-child console.log(unique(el, { selectorTypes: ['data-cy', 'nth-child'] })); // → '[data-cy="login-btn"]' // Prefer ARIA role, then class, then nth-child const modal = document.querySelector('[role="dialog"]'); console.log(unique(modal, { selectorTypes: ['attribute:role', 'class', 'nth-child'] })); // → '[role="dialog"]' // Only positional selectors const cell = document.querySelector('td.active'); console.log(unique(cell, { selectorTypes: ['nth-child'] })); // → ':nth-child(2) > :nth-child(1) > :nth-child(3)' // Use all attributes (minus ignored list) as selector source const item = document.querySelector('[data-type="primary"]'); console.log(unique(item, { selectorTypes: ['attributes'] })); // → '[data-type="primary"]' ``` -------------------------------- ### Optimize Performance with Caching Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Improve the performance of the `unique` function by providing shared caches for selectors and uniqueness checks. Reusing caches across multiple calls significantly speeds up repeated lookups. ```javascript const selectorCache = new Map(); const isUniqueCache = new Map(); const selector = unique(element, { selectorCache, isUniqueCache }); // Reuse the same caches for multiple calls const selector2 = unique(anotherElement, { selectorCache, isUniqueCache }); ``` -------------------------------- ### Element with Multiple Classes Selector Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Generates a selector for an element with multiple classes, combining them. ```html
Card
``` -------------------------------- ### Specify Allowed Selector Types Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Limit the types of selectors that can be used. Useful for enforcing specific attribute usage or simplifying selectors. ```javascript const selector = unique(element, { selectorTypes: ['id', 'class'] }); ``` ```javascript const selector = unique(element, { selectorTypes: ['data-test-id', 'data-cy'] }); ``` ```javascript const selector = unique(element, { selectorTypes: ['attribute:role', 'attribute:aria-label'] }); ``` -------------------------------- ### Element with ID Selector Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Generates a selector for an element with a unique ID. ```html ``` -------------------------------- ### Element with Data Attribute Selector Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Generates a selector for an element using its data attribute. ```html
Profile
``` -------------------------------- ### unique(element, options) Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Generates a unique CSS selector for the given DOM element. The uniqueness is determined within the element's root node context (document or shadow root). ```APIDOC ## unique(element, options) ### Description Generates a unique CSS selector for the given DOM element. Elements rendered within Shadow DOM will derive a selector unique within the associated ShadowRoot context. Otherwise, a selector unique within an element's owning document will be derived. ### Parameters #### Path Parameters - **`element`** (Element) - Required - The DOM element for which to generate a unique selector. - **`options`** (Object) - Optional - Configuration options for selector generation. ``` -------------------------------- ### Element with Custom Attribute Selector Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Generates a selector for an element using its custom attributes like role or aria-label. ```html ``` -------------------------------- ### Support for Shadow DOM Elements Source: https://github.com/cypress-io/unique-selector/blob/master/README.md The `unique` function seamlessly works with elements within a Shadow DOM. It generates selectors that are unique within the context of the shadow root. ```javascript // Works with Shadow DOM elements const shadowHost = document.querySelector('#shadow-host'); const shadowRoot = shadowHost.attachShadow({ mode: 'open' }); const shadowElement = shadowRoot.querySelector('.shadow-button'); const selector = unique(shadowElement); // Returns a selector unique within the shadow root context ``` -------------------------------- ### Element with Unique Class Selector Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Generates a selector for an element with a single, unique class. ```html ``` -------------------------------- ### Filter Traits with options.filter Source: https://context7.com/cypress-io/unique-selector/llms.txt Use the `filter` option to conditionally reject traits during selector building. This function receives the trait type, key, and value, and returning `false` skips that trait. Useful for excluding specific attributes like auto-generated IDs or whitelisting certain class names. ```javascript import unique from '@cypress/unique-selector'; // Reject IDs that look auto-generated (contain only digits) const el = document.querySelector('#user-profile'); console.log(unique(el, { filter: (type, key, value) => { if (type === 'attribute' && key === 'id') { return !/^\d+$/.test(value); // skip purely numeric IDs } return true; } })); // '#user-profile' passes; '#12345' would be skipped, falling back to class/tag // Whitelist only classes starting with 'js-' const btn = document.querySelector('.js-submit.btn.large'); console.log(unique(btn, { filter: (type, key, value) => { if (type === 'class') return value.startsWith('js-'); return true; } })); // → '.js-submit' // Reject all nth-child positioning console.log(unique(btn, { filter: (type) => type !== 'nth-child' })); // Falls back to whatever non-positional trait is unique; '*' if none found ``` -------------------------------- ### Configure required attributes for unique selectors Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Specify attributes that must appear in the generated selector, even if not strictly necessary for uniqueness. This option takes precedence over selectorTypes and filter for the specified attributes. ```javascript unique(element, { requiredAttributes: { attributeNames: ['data-component', 'data-cy'], filter: (type, key, value) => { // Exclude auto-generated component names from injection if (type === 'attribute' && key === 'data-component') { return !value.startsWith('jss-'); } return true; }, elementCache: new Map(), } }); ``` -------------------------------- ### options.attributesToIgnore Source: https://context7.com/cypress-io/unique-selector/llms.txt Exclude specific attributes from the 'attributes' selector strategy. This option allows you to prevent certain attributes from being used when generating selectors, ensuring cleaner or more specific results. ```APIDOC ## options.attributesToIgnore ### Description Exclude specific attributes from the 'attributes' selector strategy. ### Details An array of attribute names that the 'attributes' selector strategy will skip. Defaults to `['id', 'class', 'length']`. This option only affects the generic 'attributes' sweep; explicit `data-*` or `attribute:` entries in `selectorTypes` are unaffected. ### Request Example ```javascript import unique from '@cypress/unique-selector'; const el = document.querySelector('.toolbar button'); console.log(unique(el, { selectorTypes: ['attributes', 'nth-child'], attributesToIgnore: ['id', 'class', 'length', 'style', 'tabindex'] })); ``` ``` -------------------------------- ### Attribute Value Escaping with unique-selector Source: https://context7.com/cypress-io/unique-selector/llms.txt Shows how unique selector escapes special characters in attribute values to produce valid CSS attribute selector strings. This is automatically applied to generated attribute selectors. ```javascript import unique from '@cypress/unique-selector'; // Attribute value with a real newline character const td = document.createElement('td'); td.setAttribute('data-header', 'Start Date\nEnd Date'); document.body.appendChild(td); document.body.appendChild(document.createElement('td')); // sibling console.log(unique(td, { selectorTypes: ['data-header', 'nth-child'] })); // → '[data-header="Start Date\\A End Date"]' // Attribute value with double quotes const btn = document.createElement('button'); btn.setAttribute('aria-label', 'Click "here"'); document.body.appendChild(btn); document.body.appendChild(document.createElement('button')); console.log(unique(btn, { selectorTypes: ['attribute:aria-label', 'nth-child'] })); // → '[aria-label="Click \"here\""]' // Attribute value with backslash (Windows path) const el = document.createElement('div'); el.setAttribute('data-path', 'C:\\Users\\name'); document.body.appendChild(el); document.body.appendChild(document.createElement('div')); console.log(unique(el, { selectorTypes: ['data-path', 'nth-child'] })); // → '[data-path="C:\\Users\\name"]' ``` -------------------------------- ### Filter Selectors Based on Type, Key, or Value Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Implement custom logic to include or exclude selectors based on their type, attribute key, or value. This allows for fine-grained control over generated selectors. ```javascript const selector = unique(element, { filter: (type, key, value) => { if (type === 'attribute' && key === 'id') { // Only allow IDs that contain 'test' return value.includes('test'); } return true; } }); ``` ```javascript const selector = unique(element, { filter: (type, key, value) => { if (type === 'class') { // Only allow classes that start with 'btn-' return value.startsWith('btn-'); } return true; } }); ``` -------------------------------- ### Ensure Required Attributes in Selectors Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Force specific attributes to be included in the generated selector, even if they are not necessary for uniqueness. This enhances selector readability and stability by reflecting semantic component attributes. ```javascript const selector = unique(element, { requiredAttributes: { attributeNames: ['data-component'] } }); ``` ```javascript const selector = unique(element, { filter: (type, key) => key !== 'data-component', requiredAttributes: { attributeNames: ['data-component'], // No requiredAttributes.filter — all values are injected } }); ``` ```javascript const selector = unique(element, { requiredAttributes: { attributeNames: ['data-component'], filter: (type, key, value) => { if (type === 'attribute' && key === 'data-component') { return !value.startsWith('jss-'); } return true; }, elementCache: new Map(), // reuse across calls for performance } }); ``` ```javascript const selector = unique(element, { requiredAttributes: { attributeNames: ['data-cy', 'data-region'] } }); ``` -------------------------------- ### Complex Nested Element Selector Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Generates a selector for a complex nested element by traversing up the DOM tree. ```html
Hello
``` -------------------------------- ### Define a filter function for selector generation Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Use a filter function to conditionally reject traits when building selectors. The function receives the type, key, and value of a trait and should return true to allow it or false to reject it. ```javascript function filter(type, key, value) { // type: 'attribute', 'class', 'tag', 'nth-child' // key: attribute name (for attributes), class name (for classes), etc. // value: attribute value, class name, tag name, nth-child position // Return true to allow this trait, false to reject it return true; } ``` -------------------------------- ### Element Requiring Nth-Child Selector Source: https://github.com/cypress-io/unique-selector/blob/master/README.md Generates a selector for elements that require nth-child positioning due to sibling similarity. ```html
Item 1
Item 2
``` -------------------------------- ### Exclude Attributes with options.attributesToIgnore Source: https://context7.com/cypress-io/unique-selector/llms.txt Prevent specific attributes from being used in selector generation by listing them in `attributesToIgnore`. This option only affects the generic `'attributes'` strategy. ```javascript import unique from '@cypress/unique-selector'; // Ignore 'style' and 'tabindex' in addition to defaults const el = document.querySelector('.toolbar button'); console.log(unique(el, { selectorTypes: ['attributes', 'nth-child'], attributesToIgnore: ['id', 'class', 'length', 'style', 'tabindex'] })); // Only non-ignored attributes are used; falls to nth-child if none remain unique // → '[aria-label="Save"]' or ':nth-child(2)' ``` -------------------------------- ### Require Attributes with options.requiredAttributes Source: https://context7.com/cypress-io/unique-selector/llms.txt The `requiredAttributes` option ensures specified attributes are always included in the selector. It can also include a `filter` function to conditionally inject attributes based on their values. This option takes precedence over `selectorTypes` and the top-level `filter`. ```javascript import unique from '@cypress/unique-selector'; // Always include data-cy in every element's segment of the selector document.body.innerHTML = ` `; const link = document.querySelector('[data-cy="home-link"]'); // Without requiredAttributes — shortest unique selector console.log(unique(link)); // → ':nth-child(1) > .nav-link' // With requiredAttributes — data-cy woven in throughout console.log(unique(link, { requiredAttributes: { attributeNames: ['data-cy'] } })); // → '[data-cy="app"] [data-cy="sidebar"] .nav-link[data-cy="home-link"]' // requiredAttributes.filter — only inject values matching a pattern console.log(unique(link, { requiredAttributes: { attributeNames: ['data-cy'], filter: (type, key, value) => { if (key === 'data-cy') return /^(app|home)/.test(value); // skip "sidebar" return true; } } })); // → '[data-cy="app"] .nav-link[data-cy="home-link"]' // Multiple required attribute names document.body.innerHTML = `
42
`; const val = document.querySelector('.value'); console.log(unique(val, { requiredAttributes: { attributeNames: ['data-cy', 'data-region'] } })); // → '[data-region="main"] [data-cy="dashboard"] .widget[data-cy="widget-a"] > .value' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.