Skip to content
Advertisement

Select value by text from a dynamic non select dropdown using Selenium Java

I want to select value by text from a dynamic non select dropdown. I did some research and I found this code:

WebElement element = driver.findElement(ByMapper.getBy(dropdown));
element.click();
List<WebElement> options = element.findElements(By.xpath("/html/body/div[1]/div[2]/div/div/div"));
for (WebElement option : options){
    if (option.getText().contains(text)){
        option.click();
        break;
    }
}

Basically it put the dropdowns options into a List element, and run through in a for loop, and if the options contains text, click it and break the loop. However it is not working with this type of dropdown:

Snapshot:

Dropdown

Can you suggest what can I do?

Snapshot of Specific value:

Specific value

Note: The page is only available via private vpn, so I cannot share it.

Advertisement

Answer

To select the value by text Teszt_5 from a dynamic non Select dropdown you can use the following locator strategies:

String text = "Teszt_5";
WebElement element = driver.findElement(ByMapper.getBy(dropdown));
element.click();
List<WebElement> options = element.findElements(By.xpath("//div[@class='mat-autocomplete-panel mat-autocomplete-visible ng-star-inserted' and starts-with(@aria-labelledby, 'mat-form-field-label')]//mat-option//span[@class='mat-option-text']"));
for (WebElement option : options){
    if (option.getText().contains(text)){
        option.click();
        break;
    }
}

References

You can find a couple of relevant detailed discussions in:

Advertisement