Home > Enterprise >  cypress get element with more than two children
cypress get element with more than two children

Time:10-12

I have this HTML and I want to get the first element with more than 2 children. Alternatively to get the children of the first element themselves

<div >
  <button type="button" >
    <span >Option1</span>
  </button>
  <button type="button" >
    <span >Option2</span>
  </button>
</div>
<div >
  <button type="button" >
    <span >Option1</span>
  </button>
  <button type="button" >
    <span >Option2</span>
  </button>
  <button type="button" >
    <span >Option3</span>
  </button>
  <button type="button" >
    <span >Option4</span>
  </button>
</div>
<div >
  <button type="button" >
    <span >Option1</span>
  </button>
  <button type="button" >
    <span >Option2</span>
  </button>
  <button type="button" >
    <span >Option3</span>
  </button>
  <button type="button" >
    <span >Option4</span>
  </button>
</div>

CodePudding user response:

I would use the jQuery nth-child selector. If you use nth-child(3), that will only select something that has more than two, you can then select the parent of that selection and get the first matching group using eq(0). Then get all the buttons with find

cy.get(".market-template-2-columns .market-button:nth-child(3)").parent(0).eq(0)

// or, to get the child buttons
cy.get(".market-template-2-columns .market-button:nth-child(3)").parent(0).eq(0).find(".market-button")

// or using tags instead of classes
cy.get("div button:nth-child(3)").parent(0).eq(0).find("button")

CodePudding user response:

You can apply a .filter() to the parents

cy.get('.market-template-2-columns')
  .filter((index,element) => element.children.length >= 3)
  .first()    
  .children()

Or with jQuery pseudo-selectors

cy.get('.market-template-2-columns')
  .filter(':has(button:eq(3))')        
  .first()    
  .children()
  • Related