Skip to main content
aaronwilliams.me logo

Cypress DOM Traversal Commands

Following the previous post on filtering Cypress query commands this post demonstrates how to use DOM traversal commands.

Let's consider we’re querying HTML this form and want to traverse its elements.

<form>
  <button>Not Disabled</button>
  <button>Not Disabled</button>
  <button>Not Disabled</button>
  <button>Not Disabled</button>
  
  <button disabled>Disabled</button>
 
  <button>Not Disabled</button>
 </form>

children()

Query only 1 level down from the yielded subject.

For example, scope to all disabled buttons that are children of a form tag.

cy.get("form")
  .children(":disabled")

closest()

The nearest ancestor of the yielded subject. This will traverse up the DOM until an element matches the selector.

For example, yield the form element that contains the disabled button.

cy.get(":disabled")
.closest("form")

next() / prev()

Get the next or previous sibling element of the yielded subject.

For example, a button next to it.

cy.get("form")
.children(":disabled")
.next()

nextAll() / prevAll()

Get all the next or previous sibling elements of the yielded subject.

For example, yield all buttons before the disabled one.

cy.get("form")
  .children(":disabled")
  .prevAll()

nextUntil() / prevUntil()

Get all next or previous elements between the yielded subject optionally stopping at a specific selector.

For example, yield all buttons between the first one until the disabled one.

cy.get("form")
  .find("button")
  .first()
  .nextUntil(":disabled")

parent()

Get the immediate parent element of the yielded subject.

For example, yield the parent element of the disabled button.

cy.get(":disabled")
  .parent()

parents() / parentsUntil()

Get all ancestor elements of the yielded subject optionally stopping at a specific selector.

For example, yield the parent form tag of the disabled button.

cy.get(":disabled")
  .parents("form")  

Or to stop traversal when a selector is reached:

cy.get(":disabled")
  .parentsUntil("body")

siblings()

Get all sibling elements (before and after) of the yielded subject.

For example, yield all buttons in the same form as the disabled one.

cy.get(":disabled")
  .siblings("button")