Skip to main content

Cypress.SelectorPlayground

The Selector Playground exposes APIs that enable you to:

  • Change the default selector strategy
  • Override the selectors that are returned per element

Syntax​

Cypress.SelectorPlayground.defaults(options)
Cypress.SelectorPlayground.getSelector($el)

Arguments​

options (Object)

An object containing any or all of the following options:

OptionAcceptsDescription
selectorPriorityArray of stringsDetermines the order of preference for which selector is chosen for the element.
onElementfunctionA function called with the element that should return a unique selector string for the element. If a falsey value is returned, the default selector function is used.

Default Selector Priority​

  1. data-cy
  2. data-test
  3. data-testid
  4. data-qa
  5. id
  6. class
  7. tag
  8. attributes
  9. nth-child

$el (Object)

The jQuery element that you want to get the selector value for.

Examples​

Selector Priority​

Set the selector priority to favor IDs, then classes, then attributes.

Cypress.SelectorPlayground.defaults({
selectorPriority: ['id', 'class', 'attributes'],
})

onElement Callback​

Set a custom function for determining the selector for an element. Falls back to default behavior if returning a falsey value.

Cypress.SelectorPlayground.defaults({
onElement: ($el) => {
const customId = $el.attr('my-custom-attr')

if (customId) {
return `[my-custom-attr=${customId}]`
}
},
})

Get Selector​

Returns you the selector value for a given element as determined by the selector strategy.

For example, consider this HTML fragment.

<button id="bingo" class="number3">Cup of tea</button>

With the default selector strategy, the selector value will be '#bingo' because IDs have priority over classes.

const $el = Cypress.$('button')
const selector = Cypress.SelectorPlayground.getSelector($el) // '#bingo'

With a custom selector strategy that favours classes, the selector value will be '.number3'.

Cypress.SelectorPlayground.defaults({
selectorPriority: ['class', 'id'],
})

const $el = Cypress.$('button')
const selector = Cypress.SelectorPlayground.getSelector($el) // '.number3'