Locating unique element from a set of elements that only differ by a random string in the id attribute



  • I am trying to locate and loop through a set of elements that contain an id that only differs by a contained string. This contained string is not known prior to the test.

    My current attempt is to use the xpath with the contains function and then attempt to loop through the set via the element index. The set size is known in advance.

    int k;
            for(k=1;k<=maxTraveller-1;k++) {
            driver.findElement(By.xpath("(//*[contains(@id,'id_same_beneficiaries_as_above_')])["+k+"]")).click();
            }
    

    the error message I'm getting is as follows:

    Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible...
    

    Below is a sample of the HTML I am trying to select from

        <div class="col-md-7 col-lg-6 travel-field">
        <input type="checkbox" name="same_beneficiaries_as_above_1153" id="id_same_beneficiaries_as_above_1153" checked="" tabindex="8" data-pk="1153">
       </div>      
    <div class="col-md-7 col-lg-6 travel-field">
        <input type="checkbox" name="same_beneficiaries_as_above_1154" id="id_same_beneficiaries_as_above_1154" checked="" tabindex="9" data-pk="1154"> 
      </div>
    


  • Actually they differs not only in ID but also in tabIndex attribute. Also they are different in position in DOM. So you can use several approaches here:

    1. Look up for a list of elements like List inputs = driver.findElements(By.xpath("//input[@tabindex]")); or List inputs = driver.findElements(By.xpath("//input[contains(@id,'id_same_beneficiaries_as_above_')]"));

    2. Iterate through a list

      for(WebElement input: inputs){
          // Do something with input 
      }
      

      You have to design your test in the way you do know which element to interact either basing on some attribute value, or basin on positioning value. Anyway there should be some marker so that your test can locate a proper element.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2