TL;DR (summary)

.children(), .closest(), .siblings() and the other traversal commands move between parents, children and siblings in the DOM. Worked through with examples such as finding the disabled buttons in a form.

Following the previous post on filtering Cypress query commands this post demonstrates how to use DOM traversal commands. Like .find(), these are all queries, so they retry along with the rest of the chain.

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

html
<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.

typescript
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, starting with the element itself.

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

typescript
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.

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

nextAll() / prevAll()

#

Get all the next or previous sibling elements of the yielded subject. With .prevAll() the closest sibling is yielded first.

For example, yield all buttons before the disabled one.

typescript
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.

typescript
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.

typescript
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.

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

Or to stop traversal when a selector is reached:

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

siblings()

#

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

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

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