How can I locate elements using the xpath contains class in selenium?

1.5K    Asked by ananyaPawar in QA Testing , Asked on May 9, 2022

 I have below two input fields and I have to find their location I can't use class selector cause iI have to identify element based on formcontrolname and ng-invalid class



<input _ngcontent-thn-c28="" formcontrolname="nic_no" igxinput="" type="text" placeholder="00000-0000000-0" class="ng-untouched ng-pristine ng-invalid igx-input-group__input">


<input _ngcontent-thn-c28="" formcontrolname="username" igxinput="" type="text" placeholder="UserName" class="ng-untouched ng-pristine ng-invalid igx-input-group__input">

Therefore I'm using xpath. Below is what I did:
driver.findElement(By.xpath("//div/input[(@formcontrolname='nic_no') and (@class='ng-invalid')]"); 


driver.findElement(By.xpath("//div/input[(@formcontrolname='nic_no') and (@class='ng-invalid')]"); 
But I'm getting error apparently I have to write all classes name inside @class, like this:
driver.findElement(By.xpath("//div/input[(@formcontrolname='nic_no') and (@class='ng-untouched ng-pristine ng-invalid igx-input-group__input')]"); 

If I do like above then I won't get errors but I need to use only one class name, cause there are changes more classes may include and reduce from this list of classes.


Answered by Amit raj

You should use xpath contains class:


equals validates the attribute value is exactly equal to the given value. As the attribute class value is "ng-untouched ng-pristine ng-invalid igx-input-group__input" you cannot say @class="ng-invalid"
You should use contains instead
driver.findElement(By.xpath("//div/input[(@formcontrolname='nic_no') and contains(@class,'ng-invalid')]");
Or use CSS:
In css class can be mentioned as tag.classname:
 driver.findElement(By.cssSelector("div>input.ng-invalid[formcontrolname='nic_no']")
If you want to have exact class match :
you can use [attribute='value'] syntax:
 driver.findElement(By.cssSelector("div>input[class='ng-untouched ng-pristine ng-invalid igx-input-group__input'][formcontrolname='nic_no']")


Your Answer

Interviews

Parent Categories