0

HTML CODE:

<select name="ddlFruit" id="ddlFruit" class="Searchddl">
    <option value="">Select</option>
    <option value="447">Grapes</option>
    <option value="448">Mango</option>
    <option selected="selected" value="449">Apple</option>
</select>

How can i replace

selected="selected"

to other options using selenium webdriver.

Eg:

<select name="ddlFruit" id="ddlFruit" class="Searchddl">
    <option value="">Select</option>
    <option selected="selected" value="447">Grapes</option>
    <option value="448">Mango</option>
    <option value="449">Apple</option>
</select>
by dukaan
  • 17
  • 6

3 Answers3

1

You can execute js script to modify attribute:

var webDriver = new ChromeDriver();
var jsExecutor = (IJavaScriptExecutor)webDriver;
var webElement = webDriver.FindElement(By.Id('id'));
jsExecutor.ExecuteScript("arguments[0].setAttribute('selected','selected');",webElement);
Piotr M.
  • 385
  • 2
  • 8
0

Option selected Property

The selected option property sets or returns the selected state of an option.

As per the HTML:

<select name="ddlFruit" id="ddlFruit" class="Searchddl">
    <option value="">Select</option>
    <option value="447">Grapes</option>
    <option value="448">Mango</option>
    <option selected="selected" value="449">Apple</option>
</select>

The option with text as Apple is selected.


This usecase

The selected property can be replaced to other options only by selecting the other <option>.

To select the <option> with text as Grapes you need to induce WebDriverWait for the ElementToBeClickable() and you can use either of the Locator Strategies:

  • Using CssSelector and SelectByValue():

    new SelectElement(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("select.Searchddl#ddlFruit")))).SelectByValue("447");
    
  • Using XPath and SelectByText():

    new SelectElement(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("//select[@class='Searchddl' and @id='ddlFruit']")))).SelectByText("Grapes");
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0
Select dropdown = new Select(driver.findElement(By.id("identifier")))
dropdown.selectByVisibleText("option")

where identifier is a way of finding the drop down, and option is the option to select.

OctopuSS7
  • 465
  • 2
  • 9