W3cubDocs

/Cypress

root

Get the root DOM element.

Syntax

cy.root()
cy.root(options)

Usage

Correct Usage

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

Arguments

options (Object)

Pass in an options object to change the default behavior of .root().

Option Default Description
log true Displays the command in the Command log
timeout defaultCommandTimeout Time to wait for cy.root() to resolve before timing out

Yields

.root() yields the root DOM element.

The root element yielded is <html> by default. However, when calling .root() from a .within() command, the root element will point to the element you are “within”.

Examples

HTML

Get the root element

cy.root() // yields <html>

Within

Get the root element in a .within() callback function

cy.get('form').within(($form) => {
  cy.get('input[name="email"]').type('[email protected]')
  cy.get('input[name="password"]').type('password')
  cy.root().submit() // submits the form yielded from 'within'
})

Rules

Requirements

  • cy.root() requires being chained off of cy.

Assertions

  • cy.root() will automatically retry until assertions you've chained all pass.

Timeouts

  • cy.root() can time out waiting for assertions you've added to pass.

Command Log

Get root element

cy.root().should('match', 'html')

cy.get('.query-ul').within(() => {
  cy.root().should('have.class', 'query-ul')
})

The commands above will display in the Command Log as:

Command Log root

When clicking on the root command within the command log, the console outputs the following:

Console Log root

See also

© 2017 Cypress.io
Licensed under the MIT License.
https://docs.cypress.io/api/commands/root.html