Why does Cypress show 'cy.click() failed, element detached from DOM' after using findAllByRole and eq to click on an element?

Why am I getting a “cy.click() failed because this element is detached from the DOM” error in Cypress? Objective: I want to click on a particular element on the page using an accessibility selector with cypress

Code

cy.findAllByRole(‘rowheader’).eq(2).click(); Error

Timed out retrying: cy.click() failed because this element is detached from the DOM.

...

Cypress requires elements be attached in the DOM to interact with them.

The previous command that ran was:

cy.eq()

This DOM element likely became detached somewhere between the previous and current command. Question: I can see in the DOM that this element is still present - there is no logic that will detach this element from the DOM, and the eq method certainly wouldn’t do that. Additionally, the findAllByRow method is clearly working as it has found the correct th element I want to click on. How come its saying the element is detached? Is there a workaround for this situation?

Hi Kusha

To resolve the issue of Cypress reporting that the element is detached from the DOM even though it appears present, you can try the following solution.

Debugging: Add logging statements before and after the click command to verify the element’s state and any changes that might occur between locating the element and attempting to click it.

cy.findAllByRole(‘rowheader’).eq(2).then(($element) => { console.log(‘Element before click:’, $element); $element.click(); console.log(‘Element after click:’, $element); });

Hi Kusha,

To resolve the issue of Cypress reporting that the element is detached from the DOM even though it appears present, you can try the following solution.

Retry Command: Use Cypress’s retry mechanism to retry the click command on the element. This can sometimes resolve timing issues where the element is momentarily detached.

cy.findAllByRole(‘rowheader’).eq(2).click({ force: true });

Using { force: true } will force Cypress to click on the element even if it is considered detached.