Search code examples
javascriptdynamichtml-tableautomationcypress

How to locate element having dynamic ids?


I want to locate this element:

<tr class=" category-2 saleproductname  " id="21" xpath="1">
<input class="check-box" id="BillInfo_4__isSelected" type="checkbox" value="true" xpath="1">

I am trying to locate the id, but the id is dynamic, this particular item can have id="BillInfo_0__isSelected, sometimes id="BillInfo_1__isSelected and I have to keep on changing them on code. Is there any solution to this? Here only the id = 21 is unique but unable to use this as well. I am trying to use id since the class is common and locates other elements too.


Solution

  • Since id="21" is unique, query for that and use .find() (which will find within the parent) to access the input

    cy.get('tr#21')
      .find('input')
    

    In case there's several inputs in the same row

    cy.get('tr#21')
      .children()
      .eq(0)          // first child element
    

    If id="21" changes per build, it would be a good idea to add a data-cy attribute

    <input class="check-box" id="BillInfo_4__isSelected" data-cy="my-input" ... />
    
    cy.get('[data-cy="my-input"]')