Home > OS >  get element with n children
get element with n children

Time:09-12

i have the following HTML

<li data-testid="wrapper">
  <div >
    <p data-testid="selection1">
    <p data-testid="selection2">
    <p data-testid="selection3">
    ...
    <p data-testid="selectionN">

  </div>
  <button type="button" data-testid="button"></button>
  </li>

there are multiple wrappers with different amount of selections. I want to click the button on the first wrapper with exactly 3 selections

CodePudding user response:

Just use a bit of js after selecting each wrapper

const wrappers = [...document.querySelectorAll('[data-testid=wrapper]')];
const firstWrapperWith3Selections = wrappers.find((w) => w.querySelector(".selections").children.length === 3);
console.log(firstWrapperWith3Selections);
firstWrapperWith3Selections.style.backgroundColor = "red";
firstWrapperWith3Selections.querySelector("button").click();
<ul>
<li data-testid="wrapper">
  <div >
    <p data-testid="selection1">
    <p data-testid="selection2">
  </div>
  <button type="button" data-testid="button"></button>
</li>
<li data-testid="wrapper">
  <div >
    <p data-testid="selection1">
  </div>
  <button type="button" data-testid="button"></button>
</li>
<li data-testid="wrapper">
  <div >
    <p data-testid="selection1">
    <p data-testid="selection2">
    <p data-testid="selection3">
  </div>
  <button type="button" data-testid="button"></button>
</li>
<li data-testid="wrapper">
  <div >
    <p data-testid="selection1">
    <p data-testid="selection2">
    <p data-testid="selection3">
    <p data-testid="selection4">
  </div>
  <button type="button" data-testid="button"></button>
</li>
<li data-testid="wrapper">
  <div >
    <p data-testid="selection1">
    <p data-testid="selection2">
    <p data-testid="selection3">
    <p data-testid="selection4">
  </div>
  <button type="button" data-testid="button"></button>
</li>
</ul>

CodePudding user response:

const wrappers = document.querySelectorAll(".wrapper")

wrappers[0].addEventListener('click',()=>{
//Whatever you want to run // for Example :'function()'
//You must add that function to your button so whenever you click that wrapper button will work.})

CodePudding user response:

Perhaps this is what you want?

Scan through all wrappers, check how many <p> each has.

cy.get('li[data-testid="wrapper"]')
  .each($li => {
    const $p = $li.find('p')
    if ($p.length === 3) {
      cy.wrap($li).find('button').click()
    }
  })

CodePudding user response:

Apply a .filter() with a jQuery expression:

cy.get('li[data-testid="wrapper"]')
  .filter((i,li) => Cypress.$(li).find('p').length === 3 )
  .first()
  .click()

These alternatives also work:

.filter((i,li) => Cypress.$(li).find('.selections').children().length === 3 )
.filter((i,li) => Cypress.$(li).find('[data-testid^="selection"]').length === 3 )
  • Related