3

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

<div>
<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">
</div>

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

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 error but I need to use only one class name, cause there are changes more classes may include and reduce from this list of classes.

1 Answer 1

6

You should use contains:

equals validates the attribute value is exactly equal to 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']")
3
  • this worked driver.findElement(By.cssSelector("div>input.ng-invalid[formcontrolname='nic_no']") but my question is for knowledge purpose why didn't contains work? contains searches for the similar text it should have worked why didn't it?
    – anmol agha
    Nov 17, 2020 at 11:19
  • @anmolagha it should work try using just contains and see if it works
    – PDHide
    Nov 17, 2020 at 13:26
  • Please accept the answer by clicking the tick sign
    – PDHide
    Nov 17, 2020 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.