Home > Net >  How to write dynamic xpath in cypress
How to write dynamic xpath in cypress

Time:11-26

Say i have elements

 <div id="Test1">
      <p text="One"> One </p>
 </div>

 <div id="Test2">
      <p text="One">  One </p>
 </div>

 <div id="Test3"> 
      <p text="One"> One </p>
 </div>

 <div id="Test4"> 
      <p text="One"> One </p>
 </div>

Now i want to locate the text element dynamically based on div id. Something like

getText(divID){

cy.get("divID").find("vasErrorMessage").; }

How to write code in cypress for this. Here i will send divID dynamically and divID can be Test2 or Test1

CodePudding user response:

When using an Id as CSS selector, it needs to be prefixed with a hash.

getElementById(id) {
    const selector = "#"   id;
    return cy.get(selector);
}

There is no need for xpath, which is not supported by Cypress out of the box.

CodePudding user response:

You can use .contains() to get the proper element.

// gets third id=Test3 element with 'One' text
cy.contains('#Test3', 'One')
  • Related