In my scenario, I am clicking on a dropdown selection, which yields the child elements to be clicked on. I am wanting to click on the first element/option, here's my approach which is working.
cy.get( 'ul[role="listbox"]' ).children().each(( $btn, index ) => {
// clicks first option in dropdown
if( index === 0 ) {
cy.get( $btn ).click();
}
});
The reason I'm doing it like this, is when I try to click directly on the element without iterating through the children, I'll sometimes get the error "cy.click()` failed because this element is detached from the DOM."
But the way I have it implemented now, the error does not occur.
HTML for the dropdown (has 2 options in this case, can be any amount):
<div role="listbox" >
<ul role="listbox" tabindex="0" data-baseweb="menu" id="bui-3" aria-multiselectable="false" >
<li role="option" aria-disabled="false" aria-selected="false" id="bui-5" >
<div aria-selected="false" >Dropdown Option 1 </div>
</li>
<li role="option" aria-disabled="false" aria-selected="false" id="bui-6" >
<div aria-selected="false" >Dropdown Option 2 </div>
</li>
</ul>
</div>
CodePudding user response:
Have you tried finding the first li
, using Cypress' .find()
command? I would guess that this would work and hopefully not give you the error message described.
cy.get( 'ul[role="listbox"]' )
.find('li') // searches for all `li` underneath the yielded element
.eq(0) // selects the item at the index
.click();