Dropdown options are not getting selected (select 2) using SELENIUM and JAVA

I’ve been trying without success to select an option from a dropdown select 2 class.

<span class="select2-selection__rendered" id="select2-OperativeUnit_Id-container" title="Newsan">Newsan</span>

I did this then in Selenium and the dropdown is selected:

driver.findElement(By.xpath("//*[@id=\"select2-OperativeUnit_Id-container\"]")).click();

The problem is that i can select no option at all. The dropdown has this:

<ul class="select2-results__options" role="tree" id="select2-OperativeUnit_Id-results" aria-expanded="true" aria-hidden="false">
<li class="select2-results__option select2-results__option--highlighted" id="select2-OperativeUnit_Id-result-1jq8-81" role="treeitem" aria-selected="true">Company1</li>
<li class="select2-results__option" id="select2-OperativeUnit_Id-result-fjep-281" role="treeitem" aria-selected="false">Company2</li>
<li class="select2-results__option" id="select2-OperativeUnit_Id-result-e8a1-408" role="treeitem" aria-selected="false">Company3</li>
</ul>

What should i do to select the option "Company2"?

>Solution :

Instead of

driver.findElement(By.xpath("//*[@id=\"select2-OperativeUnit_Id-container\"]")).click();

Try

driver.findElement(By.xpath("//li[contains(.,'Company2')]")).click();

You can make the locator more precise with this:

driver.findElement(By.xpath("//li[@class='select2-results__option' and contains(.,'Company2')]")).click();

Leave a Reply