'How to click elements that have generated id's if I don't know what the ID will be in Selenium
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
Solution 1:[1]
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]
Solution 2:[2]
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
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | JeffC |
Solution 3 | Akash Bhatia |