Tiago Machado
Tiago Machado

Reputation: 394

Selenium - How do I get the the list of options of a drop down list using java?

I have the following code:

<span class="dropDown">Choose</span>
<div class="dropdownQuestions active" style="display: block; max-height: 310px;">
<span data-index="0" data-value="1" onclick="gt.setQuestion(this, true);">Warrior</span>
<span data-index="1" data-value="2" onclick="gt.setQuestion(this, true);">Mage</span>
<span data-index="2" data-value="3" onclick="gt.setQuestion(this, true);">Sorcerer</span>

And what I want, if possible, is a list of the the drop down list so after I can use one of them to click, I have searched a lot and could not find any answer that would help me.

Other option would be to click using the data-index, or data-value String. the last option I would want is clicking by the String "Warrior", "Mage" or "Sorcerer", but if there is no other way, Ill be glad with that.

thanks!

Upvotes: 0

Views: 981

Answers (2)

mkhurmi
mkhurmi

Reputation: 816

After clicking on the dropdown, you can get all the dropdown options in a list and later use them as you want(looping and selecting the desired option with specific condition or getting option by index).

  List<WebElement> options= driver.findElements(By.xpath("//span[@class='dropDown']/div/span"));
  options.get(1).click(); // here 1 is the index value of the option to select or you can use loop if looking for some specific condition

For the image link you shared in the comment, try the following cssSelector:

List<WebElement> option= driver.findElements(By.cssSelector("div.questionDropdownOptions.activeSelectMenu span"));
                option.get(1).click();
    }

Note: Please import below packages in your code:

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

Upvotes: 1

StyleZ
StyleZ

Reputation: 1273

I think that all what are you looking for has already been answered here:

-> How to select a dropdown value in Selenium WebDriver using Java

and if you want to iterate through it, this might be helpful

-> How to count the number of options in a select drop down box in Selenium WebDriver using Java?

To be more specific, in a first link, you can see that you can click on the dropdown option using String parameter and also you can use an index.

I know you were probably looking for a specific code, but sadly, I am not on a computer, but I am pretty sure that this answer's your question.

Good luck with your code :)

Upvotes: 0

Related Questions