1

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">
1
  • Is name="startTimeHours" not unique on the page? Commented Mar 19, 2019 at 15:53

6 Answers 6

4

Quick answer

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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']"));
    

Comments

1

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')]"));

Comments

1

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')]

Comments

1

Use contains, sibling or Ancestor when the value is dynamic.

xpath - //input[contsins(@id,'start-time-hours-c')]

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.