3

I want to locate an element by its id in my webpage which is a text field where I enter a name. So the element is :

<input type="text" id="a110_name" name="name" maxlength="255">

The first time, my test works well. If I add a loop to click again to the element, selenium does not find because the id has changed.

ex: the id is changing each time I click on it.

<input type="text" id="a110_name" name="name" maxlength="255">
<input type="text" id="a120_name" name="name" maxlength="255">

my code:

driver.findElement(By.id("a110_name")).sendKeys("test");

How can I resolve this problem?

1
  • I resolved with //input[contains(@id,'name')] Commented Oct 29, 2014 at 18:21

3 Answers 3

2

Good to hear that you have solved it using XPATH. You can solve this using CSS locator as below:

driver.findElement(By.cssSelector("input[id$='_name']"));

We have to use XPATH's "contains" keyword with caution, in some cases it might match some other element. If you are more comfortable XPATH, better to use //input[ends-with(@id,'_name')]

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

Comments

1

Identify Element by containing Text

If the dynamic elements have a definite pattern to them, then we can also use JavaScript functions like “starts-with” or “contains” in our element locators to separate the dynamic part of locator from static part.

For example, in case of Id example which you provided, we can use ‘contains’ function to access this locator irrespective of its dynamic part.

XPath: //input[contains(@id, '_name')]

Comments

0

Using CSS, this will also work: input[id *=_name] This means: if it contains '_name'

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.