I have a input text box having id property and the HTML for it as shown below

username:<input type="text" id="1234"><br> 

Id property is dynamically changing. when the page loads next time.

Username:<input type="text" id="5678"><br> 

and the value continuously changing.

how to write the XPath for the above scenario.

Here we have only one ID property no other properties are available. I know we can use contains,starts-with or write absolute XPath helps in other cases.

Please help me on this.

  • 2
    Share your HTML code please. With parents.
    – Sagar007
    May 26 '17 at 13:08
  • Will CSS locators work? Can you ask developers to add a name? May 26 '17 at 14:07
  • 2
    Seeing the HTML code would help tremendously, as Sagar007 mentioned above, but barring that, this might work (untested): //*[contains(text(),'Username:')]/input May 26 '17 at 15:01

How I handle dynamic IDs:

  1. Inspect the element using Chrome's DevTools
  2. Edit the element and remove the id="..." attribute
  3. Right-click the element
  4. Select "Copy" > "Copy selector" (or you could do XPath if you really want)

You now have a selector that doesn't use the ID attribute, but most likely it's DOM position. Something like "body > div:nth-child(1) > input" instead of "#1234".

2020 UPDATE: I don't do this anymore and do what Bill said which is //*[contains(text(),'Username')]/input. That translates to:

  • // anywhere in the DOM
  • * any tagName
  • [contains(text(),'Username')] where the text value contains 'Username'
  • /input the following <input>
  • 1
    @kirbycope...thank you! Save a lot of time for this beginner
    – Johnny Wu
    Jan 27 '21 at 18:12

You can try this:


In such case I talk to a developer to introduce a fixed way to locate an element, e.g., by name attribute:

Username: <input type="text" id="5678" name="username"><br> 
  • or appending the random part of an id to a fixed one like userinput+5678. No need to introduce an entirely new tag.
    – Leon
    Jul 5 '17 at 7:50
  • @Leon. New tag doesn't cost much and using new tag will make locators clear, e.g. By.name("username").
    – dzieciou
    Jul 5 '17 at 8:09
  • Of course, didnt say it cost something but no need to clutter up code there either. The same line that introduces the random value could be made to include a fixed part as well, no need for new lines of code.
    – Leon
    Jul 5 '17 at 10:15

Xpath provide following-sibling functionality with text :

Solution :

First we identify text element and then find following sibling.

Try this xpath :


Note : Here change initial * with parent of your input element like div or form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.