Skip to content
Advertisement

How to find one of many selectors that contain another nested selector

I have a web page and there is a list with multiple elements:

First type of element:

<li class="comp-data-text"> </li>
    <span class="imstuck" data-bind="text"> Something </span>

Second type of element:

<li class="comp-data-text"> </li>

As you can see the second one does not contain the “imstuck” class as well as the “Something” text. (this is an example, in real case the second line of code is nested deeper)

I want to find out which element does or does not contain this line of code. Based on the cypress documentation and a few existing topics I tried:

cy.get(...).each(($item) => {
    if ($item.has('span.imstuck')) {
        cy.wrap($item).find('.imstuck').should('contain', 'Something')
    }
})

The Cypress GUI runs the code related to if statement even if the element doesn’t contain an ‘imstuck’ class.

AssertionError
Timed out retrying after 10000ms: Expected to find element: .imstuck, but never found it.
 Queried from element: <li.comp-data-text>

I also found another way but it also works like the previous example:

cy.get(...).each(($item) => {
    if ($item.hasClass('.imstuck')) {
        cy.wrap($item).find('.imstuck').should('contain', 'Something')
    }
})

Expected result: If the particular element does not contain an ‘.imstuck’ class the if statement won’t run the third line of code.

Actual results Error pops up because each time cypress run third line of code even if a particular element doesn’t contain ‘imstuck’ class and when cypress tries to find class ‘imstuck’ from third line, cypress spits off an error.

Advertisement

Answer

Add .length to your if statement

cy.get('li').each(($li) => {
  if ($li.has('span.imstuck').length) {
    cy.wrap($item).find('.imstuck').should('contain', 'Something')
  }
})

But may be better to move 'span.imstuck' up a level. This way you are only getting those element with the span.

cy.get('li span.imstuck').each(($span) => {
  cy.wrap($span).should('contain', 'Something')
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement