top of page

Cypress: Save and Use Elements in Context

In Cypress, you can save a selected DOM element (the subject) using tools like:


  • .as() – to give it a reusable alias

  • .then() – to access and work with the raw DOM or jQuery element

  • wrap() – to re-wrap a DOM element back into a Cypress chain


We'll apply all of this using the actual elements from your working login page at: https://www.radeksto.com/test/login


1. Save an Element Using .as()

You can assign any Cypress command result to an alias using .as('name'), and later refer to it with @name.

2. Use .then() for Context-Aware Access

.then() lets you work with the subject inside a callback — helpful for direct access or debugging.


3. Full Example: Save and Reuse Login Section


When to Use What

Use Case

Method

Example

Reuse element later

.as()

cy.get(...).as('alias')

Work inside callback

.then()

cy.get(...).then(($el) => {...})

Convert raw DOM to Cypress

cy.wrap()

cy.wrap($el).find(...)


Tip: Don't Chain from .then() Directly

You can’t do something like this:

Instead, use wrap() to bring it back into a Cypress chain:


 
 
bottom of page