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++) {

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

1 Answer 1


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<WebElement> inputs = driver.findElements(By.xpath("//input[@tabindex]")); or List<WebElement> 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.

  • This solution worked. The root of my issue was that the first element in my set was hidden. I wasn't expecting a hidden element. So in addition to the above method, I added an if-else statement to ignore hidden elements. I suspect that my about method would work embedded in an if-else block, but I like the list object as a neat way to hold sets of elements especially if the size is not known in advance.Thank You.
    – Trevor Pye
    Commented Sep 21, 2018 at 18:46

Your Answer

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

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