Prashant Bellale
Prashant Bellale

Reputation: 35

Unable to select element by id

I have written a code to select a element by id but it is not getting select. I think id is changing every time.

Code I have written

Select Employmenttype = new Select(driver.findElement(By.id("ApplicantCurrentEmploymentAndIncomes_9341d691-b0c9-4d78-aa32-6b68150c42c9__EmploymentType")));     
Employmenttype.selectByValue("10");

HTML code 1st time

<select name="ApplicantCurrentEmploymentAndIncomes[9341d691-b0c9-4d78-aa32-6b68150c42c9].EmploymentType" class="DropDownEmploymentType" id="ApplicantCurrentEmploymentAndIncomes_9341d691-b0c9-4d78-aa32-6b68150c42c9__EmploymentType" style="border: 1px solid rgb(255, 0, 0); border-image: none;" jQuery18305642460436448337="196"><option value="" selected="">- Select -</option>

Id changed on 2nd time

<select name="ApplicantCurrentEmploymentAndIncomes[48770411-31e6-4f7f-bff6-08e9ed853194].EmploymentType" class="DropDownEmploymentType" id="ApplicantCurrentEmploymentAndIncomes_48770411-31e6-4f7f-bff6-08e9ed853194__EmploymentType" style="border: 1px solid rgb(255, 0, 0); border-image: none;" jQuery18305642460436448337="196"><option value="" selected="">- Select -</option>

Can anyone suggest me in this case how I can select element?

Upvotes: 1

Views: 258

Answers (1)

Cosmin
Cosmin

Reputation: 2394

You have a dynamic id. You should locate your element by using xpath, so the following code should do the trick:

Select Employmenttype = new Select(driver.findElement(By.xpath(".//select[contains(@id,ApplicantCurrentEmploymentAndIncomes)]")));     
Employmenttype.selectByValue("10");

This way, you're "telling" the driver to locate a Select tag node in your html whose id contains that particular text.

EDIT: Adding this here for visibility. Xpath is an extremely powerful tool if used to it's full potential. You can check more examples here: w3schools.com/xsl/xsl_functions.asp

Upvotes: 2

Related Questions