Select Hidden Or Visible Elements
📺 Watch this recipe explained in the video Select Hidden Or Visible Elements.
Select hidden elements
<ul id="people">
<li>Joe</li>
<li style="display:none">Ann</li>
<li>Mary</li>
<li style="opacity:0">Chris</li>
</ul>
You can find all invisible elements in the DOM using the jQuery selector :hidden. Note: Cypress considers elements with opacity:0
to be hidden.
cy.get(':hidden')
.map('innerText')
.should('deep.equal', ['Ann', 'Chris'])
You can use :hidden
with the cy.filter command.
cy.get('li')
.filter(':hidden')
.map('innerText')
.should('deep.equal', ['Ann', 'Chris'])
Tip: avoid matching stray elements by using a selector + :hidden
combination. For example, to find all hidden <LI>
elements inside the #people
list, use the precise selector:
cy.get('#people li:hidden')
.map('innerText')
.should('deep.equal', ['Ann', 'Chris'])
Select visible elements
<ul id="people">
<li>Joe</li>
<li style="display:none">Ann</li>
<li>Mary</li>
<li style="opacity:0">Chris</li>
</ul>
You can find all visible elements in the DOM using the jQuery selector :visible. Note: Cypress considers elements with opacity:0
to be hidden.
cy.get('#people li:visible')
.map('innerText')
.should('deep.equal', ['Joe', 'Mary'])
Note: finding visible elements might return a lot of elements, including the parent elements in the DOM tree. In our example visible elements include the parent list element <UL>
plus the individual <LI>
elements.
cy.get(':visible')
.map('nodeName')
.should('deep.equal', ['UL', 'LI', 'LI'])