Cypress root command

Profile picture for user arilio666

Cypress root command fetches the root DOM element. Which means this command is used to fetch the root element of a webpage from where the origin tag was created.

  • Simply put, it gets the root of a grown tree buried within the ground.
  • It can also be coupled mainly with the within command to yield its root.
  • By default, the root DOM element yielded by this command is <html>.
  • When calling .root() from a .within() command, the root element will point to the element you are "within".



Some of the options we can include in the command can be a timeout, log, etc.

  • Log: To display the command in the command log.
  • Timeout: Wait for some particular thing to get finished before timing out.

Correct Use

cy.root() --> Yield root element <html>

cy.get('li').within(($li) => {
  cy.root() // Yield root element <li>

When inside within the root element will point out to the element we are "within."

Let us check out various root command examples.

Example 1: Using Plain cy.root()

Let us check out what cy.root() does when executing it plainly without using it within command.

In this article, we will be using the login page for the root command.

it('Visit Page',() => {

As we can see, it has yielded <html> element.

Example 2: Using Assertion

it('Visit Page',() => {
    cy.root().should('match', 'html')

As we can see, it has been asserted that the yielded element is HTML.

Example 3: Form Interaction With Root

it('Visit Page',() => {
  • We are first visiting the respective page.
  • Then we isolate a part of the form with the within command and create a parameter $form.
  • Now we are fetching the CSS selectors of the username and password field.
  • Using root now as it submits the form yielded from within.
  • Submit command is used in forms to submit within that form scope automatically.

We can see that root yields here from within command.