Cypress how to get all children element from the parent element but no grand children

Viewed 1821

Cypress how to get all children element from the parent element but not grand children getting those two button directly from the body but not the sub/grand child(ren) from the form

For example

<body>
 <button></button>
 .
 .
 .
 <button></button>
 <form>
   <button></button>
   .
   .
   .
 </form>
</body>
3 Answers

It should be as simple as specifying the direct descendants only with parent > child selector

Please try this

cy.get('body > button')
  .its('length')
  .should('eq', 2)  

You need to be specific about the children you are looking for,

cy.get('body').children('button')

for instance,

<body>
  <button>C1</button>
  <button>C2</button>
  <div>D</div>
  <form>
    <button>GC</button>
  </form>
</body>
cy.get('body').children('button')
  .invoke('text')
  .should('eq', 'C1C2')

Checking immediate parent

I was also looking for a way to specify the parent is <body>.

There's no native Cypress way, but you can add a jQuery expression

Cypress.$.expr[":"].parentIs = function(el, idx, selector) {
  return Cypress.$(el).parent().is(selector[selector.length - 1]);
}

cy.get('button')
  .filter(':parentIs(body)')

You can apply a combination of children() and not to get the two children instead of three.

cy.get('body').children('button').not('form')

Test runner screenshot

In case you want to get specific children element you can use the .eq() command:

cy.get('body').children('button').eq(0) //yields first button
cy.get('body').children('button').eq(1) //yields second button

You can also use filter() if your buttons have unique texts. This in my opinion is a much cleaner way-

cy.get('body').find('button').filter(':contains("buttontText")')
Related