0

I have two fields with the same id on a single HTML page (using Angular) How to I distinguise between the two without creating a collection and referring to the indexes>

An example of one field is below

I've tried this

#content-container > inv-sidebar-layout-content > ng-component > ng-component > section > div.row.tab-container > as-split > as-split-area:nth-child(1) > article > inv-people-tabs > inv-vertical-tabs-list > div.tab-content-container > div > inv-tab:nth-child(7) > div > inv-people-contact-details-tab > section > div.left-column > inv-person-contact-details > section > inv-address-edit > section > div:nth-child(2) > input

but it's too long and cumbersome

The HTML for the first field is

<input _ngcontent-gec-c113="" class="inv-input" id="towncity" formcontrolname="TownCity">

and for the second it is

<input _ngcontent-gec-c113="" class="inv-input ng-pristine ng-valid ng-touched" id="towncity" formcontrolname="TownCity" ng-reflect-name="TownCity">
supputuri
  • 13,644
  • 2
  • 21
  • 39
RShome
  • 489
  • 2
  • 11
  • 35
  • 4
    You should find a way to make each `id` [unique](https://stackoverflow.com/q/9454645/1009922). – ConnorsFan May 29 '19 at 14:08
  • https://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme – Alexander Staroselsky May 29 '19 at 14:14
  • @ConnorsFan That's nice if you own the site or can advocate for that fix but some people don't have that option. – JeffC May 29 '19 at 17:31
  • Need more context on those two elements. Why is the same TownCity element appear on the page twice? Is it desktop vs mobile versions? Is it two different forms, each of which have it? You need to find an element in the ancestors that is different (preferably with an ID) and use that to distinguish them, e.g. `#mobile #towncity` vs `#desktop #towncity`. – JeffC May 29 '19 at 17:33
  • Agree 100% with @ConnorsFan. The site is currently not W3C compliant HTML, it should be fixed. – Ardesco May 31 '19 at 11:10

1 Answers1

1

The elements have different classes so you can distinguish them using class attribute

Example selectors:

  1. First element:

    //input[@id='towncity' and not(contains(@class,'touched'))]
    

    enter image description here

  2. Second element

    //input[@id='towncity' and contains(@class,'touched')]
    

    enter image description here

More information:

Dmitri T
  • 159,985
  • 5
  • 83
  • 133
  • In general, yes but I'm guessing that those classes are tracking state so they may appear/disappear and leave the element locator unable to find it. – JeffC May 29 '19 at 17:30