Skip to content
Advertisement

Cypress select li and click on child span

I am trying to select li and click/check on span which is checkbox but, can’t do that.

Here, following I tried.

<div id="list-widget">
    <ul class="tree">
    <li class="tree-switcher-close"> .... </li>
    <li class="tree-switcher-close">     
      <span class="tree-checkbox">  //I want to Click on this
        <div class="container">
         <span class="checkmark"></span>
        </div>
      </span>
      <span title="abc Account">
        <span class="tree-title">abc Account</span>
      </span>
     </li>
     <li class="tree-switcher-close"> 
       <span class="tree-checkbox"></span>
       ....
     </li>
     <li class="tree-switcher-close"> 
      <span class="tree-checkbox"></span>
      .... 
     </li>
    </ul>

Here, in above code I want to select li where “abc account” and once found want to click on span which have class tree-checkbox. So, I tried.

cy.get('div[id*="list-widget"]')
        .find('li')
        .contains('abc Account')
        .get('.tree-checkbox').click({force: true});

But, it says there are multiple elements found. above code find the li which have contains(‘abc Account’) but, can’t span within that li.

Advertisement

Answer

The main problem is with .get('.tree-checkbox'). It “forgets” all the preceding path, so you might as well start with cy.get('.tree-checkbox') and of course that gives multiple elements.

Change that to .find('.tree-checkbox').

Also combine li and abc Account in one selector, because .contains('abc Account') by itself takes you to the <span class="tree-title">abc Account</span> which has no tree-checkbox.

cy.get('div[id="list-widget"]')
  .find('li:contains("abc Account")')
  .find('.tree-checkbox')
  .click({force:true});

Other variation that works (but is more verbose)

cy.get('div[id*="list-widget"]')
  .find('li')
  .contains('abc Account')
  .parent()
  .parent()
  .find(".tree-checkbox")
  .click({force:true})
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement