Jin
Jin

Reputation: 99

How to iteratively click all elements in a dropdown with selenium?

I am testing a react.js front end web application with selenium and C# automation framework, I need to click all the elements in a drop down list, ideally, I would like to select the drop down as a list of elements, and iterate through each element and click it.

I have tried to locate the dropdown menu By Xpath, Cssselector, cssName, none seems to work, when I debug the code, my "dropDown" variable is always null

Here is the code of the drop down menu

<div class="dropdown-menu shadow px-4 show">
  <div>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="1">1 </label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="2">2</label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox"value="3">3</label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="4">4</label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="5">5</label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="6">6</label>
      </div>
</div>

here is my selenium code

public static IList<IWebElement> dropDownClick (IWebDriver _driver) {
  IList<IWebElement> dropdown = _driver.FindElements (By.ClassName ("dropdown-menu shadow px-4 show"));
  return dropdown
}

I expected the variable "dropdown" is not null when I run the code in debug mode

Upvotes: 0

Views: 648

Answers (3)

Santhanaprabha
Santhanaprabha

Reputation: 11

Please try with below xpath. May be it is because of sapce,

//div[contains(@class,'dropdown-menu')]//label 

Upvotes: 0

PRERNA PAL
PRERNA PAL

Reputation: 391

Please use code written below in order to get the elements and to click on each element in iteration:

//Below line Finds the dropdown 
WebElement dropdownElement = driver.findElements(By.xpath("//div[contains(@class,'dropdown-menu')]"));

//Below line stores all elements present in dropdown in a list of webelements
List<WebElement> elements = driver.findElements(By.xpath("//div[contains(@class,'dropdown-menu')]//label"));

for(WebElement ele : elements){
    //To click on dropdown
    dropdownElement.click();

    //To click on label present in dropdown. This will change with each Iteration
    ele.click();

}

Hope it helps :)

Upvotes: 1

Dazed
Dazed

Reputation: 1551

For xpath why not just use:

 //div[@class='dropdown-menu shadow px-4 show']//label ---yields 6 rows

If this is not working, make sure the drop down is not in an iframe. You need the //label added so all elements appear in your "FindElements". Without it your return is 1.

Upvotes: 0

Related Questions