Search code examples
getcss-selectorslocationcypressparent-child

How to get child element from parent element having multiple same items?


I am stuck at child element location. The attributes of child elements are having multiple items, also attributes of parent element are multiple items. I am finding difficulty in locating child element. Element action click() is not working.

Html:

<div class="locale-selector" xpath="1">
<span class="locale-selector-heading"> Your location and language</span>
<div class="locale-selector-country-wrapper" data-metrics-section="Site_lvl1_LocLangSelector">
   <a href="#" class="locale-selector-country" aria-controls="localization-container" aria-haspopup="true" aria-expanded="false">
       <div class="locale-selector-flag-heading-wrapper">
           <span class="flag-header-global flag-hong-kong"></span>
           <span class="locale-selector-country-heading">Hong Kong</span>
       </div>
       <span class="locale-selector-chevron-arrow"></span>
   </a>
</div>
</div>

span tag having multiple classes,div tag having multiple same classes.

How can I perform click() action on class ?

class="locale-selector-country-heading"

My attempt:


cy.get('.locale-selector-country-heading').contains('Hong Kong').click()

Error:

<span class="locale-selector-country-heading">Hong Kong</span>

This element <span.locale-selector-country-heading> is not visible because its parent <div.locale-selector-flag-heading-wrapper> has CSS property: visibility: hidden


Solution

  • The error is telling you that a parent element is making the whole section of the DOM tree not actionable.

    You can force the click, to turn off actionability checks

    cy.get('.locale-selector-country-heading').contains('Hong Kong').click({force:true})
    

    but then your test is somewhat not realistic - the user can't click something that's not visible.

    However, sometimes the actionability checks are incorrect - if you can actually see the element, go ahead and use {force:true}.

    Otherwise, the element may be transitioning into a visible state (via CSS animation).

    In this case, you want to add a retry on the visibility with .should('be.visible')

    cy.get('.locale-selector-country-heading').contains('Hong Kong')
      .should('be.visible')
      .click()
    

    There's a section on actionability here Interacting with Elements