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')]"));
name="startTimeHours"not unique on the page?