How can I return all the options of the select dropdown?

Viewed 231

I want to return all the options of the dropdown menu

HTML Code:

<select class="custom-select ng-pristine ng-untouched ng-valid ng-not-empty" ng-model="Air.Class" aria-invalid="false">
    <option value="0">All</option>
    <option value="F">First Class</option>
    <option value="C">Business Class</option>
    <option value="Y">Economy</option>
    <option value="W">Economy Premium</option>
    <option value="M">Economy Standard</option>
</select>

Code:

public List<WebElement> ddgetOpt(WebElement a) {
    Select drp = new Select (a);
    List<WebElement> opt = drp.getOptions();
    for (WebElement we : opt) {
        String name = we.getText();
    }
    return opt;
}

But it doesn't return the options of the Dropdown menu...

I have tried using the name also, but it returns only the last element of the Dropdown menu

2 Answers

You need to add the texts to a new list and return it

public List<String> ddgetOpt(WebElement a) {
    Select drp = new Select (a);
    List<WebElement> opt = drp.getOptions();
    List<String> texts = new ArrayList<>();
    for (WebElement we : opt) {
        texts.add(we.getText());
    }
    return texts;
}

the following method gets a dropdown webelement and returns all its options as a list of strings.

public List<String> getDropDownOptions(WebElement e) {
                    e.click();
                    Select select = new Select(e);

            return select.getOptions().stream().map(WebElement::getText).collect(Collectors.toList());
        }
Related