Reputation: 11
Say I have some HTML mark-up as such:
<select id="select_titleOfSelect-1212_01" name="titleOfSelect-1212"
<option value="ONE"></option>
<option value="TWO"></option>
<option value="THREE"></option>
</select>
Multiple of these select elements can be generated dynamically
in which the number after titleOfSelect
can always be different.
Also the "01" will increment by 1 if there is more than one select generated on the same page.
I have been able to click on these using this:
.click('select[id^="titleOfSelect-"] option[value='ONE']')
How can I click on the 2nd, 3rd, so on.. select element on the page if there is more than one?
I'm using Javascript with Selenium
Upvotes: 1
Views: 208
Reputation: 44
You can simply use the findElements
method to find the locator id^="titleOfSelect-"
. This will return ReadOnlyCollection<IWebElement>
which you can convert to a list and then target whatever index
you want to target.
Upvotes: 0
Reputation: 25619
You can use :nth-of-type()
to pick which SELECT you get, e.g.
select:nth-of-type(2) option[value="TWO"]
would select the OPTION that contains the value 'TWO' in the second SELECT
Upvotes: 1
Reputation: 5909
You don't search for the element based on its ID if the ID is randomly generated. You'll have to use an XPath or CSS selector and get creative.
Here's how I would click on the options:
// option 1
driver.findElement(By.xpath("//select/option[@value='ONE']")).click();
// option two
driver.findElement(By.xpath("//select/option[@value='TWO']")).click();
// etc..
Or, if you don't want to use value
, you can use the index:
// click first option
driver.findElement(By.xpath("//select/option[1]")).click();
// click second option
driver.findElement(By.xpath("//select/option[2]")).click();
// click third option
driver.findElement(By.xpath("//select/option[2]")).click();
If there are multiple select
elements on the page, you can try to do a contains
query on the title:
//select[contains(@title, 'titleOfSelect')]/option[1]
Upvotes: 1