How do I locate the input element by id where the last 2 numerical digits change randomly?
<input id="start-time-hours-c31" class="focused" name="startTimeHours" value="" placeholder="hh" maxlength="2" type="text">
How do I locate the input element by id where the last 2 numerical digits change randomly?
<input id="start-time-hours-c31" class="focused" name="startTimeHours" value="" placeholder="hh" maxlength="2" type="text">
When last 2 numerical digits change randomly,
driver.findElement(By.xpath("//input[contains(@id,'start-time-hours-c')]"));
Using 2 attributes of Input tag,
driver.findElement(By.xpath("//input[@name='startTimeHours' and @class='focused']"));
Please let us know if it resolved your query.
As the last 2 characters of the id
attribute changes randomly, additionally you need to consider some other attributes as well and you can use either of the following Locator Strategies:
cssSelector:
WebElement elem = driver.findElement(By.cssSelector("input[id^='start-time-hours-c'][name='startTimeHours']"));
xpath:
WebElement elem = driver.findElement(By.xpath("//input[starts-with(@id, 'start-time-hours-c') and @name='startTimeHours']"));
As the html also has a name
tag you can find the element by using that name tag, like:
WebElement element = driver.findElement(By.name("startTimeHours"));
And if the name
tag startTimeHours
is not unique on the page, then you can find the element by using the below xpath:
WebElement element = driver.findElement(By.xpath("//input[contains(@id,'start-time-hours')]"));
Agreed with @TheSociety answer, you can also be used as the combination of name and id
//input[contains(@id,'start-time-hours-c') and contains(@name,'startTimeHours')]
Use contains, sibling or Ancestor when the value is dynamic.
xpath - //input[contsins(@id,'start-time-hours-c')]
You can use either of them:
//input[starts-with(@id,'start-time-hours-c')]
(or)
//input[contains(@id,'start-time-hours-c')]
if the above returns a single webelement then you can use it or else if it returns multiple elements go for name attribute in the xpath.