Reputation: 546
I found a few answers about this but they did not answer my question an so I am writing a new question.
I have HTML code having below kind of checkbox elements (in browser's inspect element)
<input role="checkbox" type="checkbox" id="jqg_TransactionFormModel501EditCollection2_147354_grid_-1274" class="cbox" name="jqg_TransactionFormModel501EditCollection2_147354_grid_-1274" value="true">
In my test case I want to click on checkbox using its ID using Selenium Webdriver.
here Id= "jqg_TransactionFormModel501EditCollection2_147354grid-1274" is dynamic.
in above id, Bold & Italic marked letters (dynamic) will change with different check boxes in same page as well as page refresh.
Bold marked letters (dynamic) will change on page refresh only (remain same through all the check boxes in same page.)
How shoud I format/write XPATH so that I can click on desired check boxes using below statement.
WebElement checkbox = webDriver.findElement(By.id("idOfTheElement"));
if (!checkbox.isSelected()) {
checkbox.click();
}
Thanks for your help in advance.. !
Upvotes: 1
Views: 3233
Reputation: 46
I recommend not using ID's or xpath and adding a data attribute to your elements. This way, you can avoid the annoyance of xpath and have a strong selector that you feel confident will always be selectable.
For example, you could call the attribute: data-selector. You can assign a value of "transactionFormModelCheckbox". Then, when creating a new element, you create by css selector with the value referenced above.
No matter what type of formatting, you'll always be able to select that checkbox - as long as the element exists in the DOM. If you need to investigate other attributes, you can use the selector to do things like hasClass() or anything else you need.
Hope that helps !
Upvotes: 0
Reputation: 841
Here are a few examples of xpaths which you can use to find your checkbox
//input[contains(@id,'jqg_TransactionFormModel')]
OR, if you want more checks, try something like
//*[starts-with(@id,'jqg_TransactionFormModel') and contains(@id,'EditCollection2_')]
Additionally, you can try regex as well using matches
//*[matches(@id,'<regex matching your id>')]
Upvotes: 1
Reputation: 1194
You can write xpath like this :
//input[starts-with(@id,'jqg_TransactionFormModel')]
//input[contains(@id,'jqg_TransactionFormModel')]
Upvotes: 0
Reputation: 50949
You can use partial ID using cssSelector
or xpath
webDriver.findElement(By.cssSelector("[id*='TransactionFormModel']"));
webDriver.findElement(By.xpath("//input[contains(@id, 'TransactionFormModel')]"));
You can replace TransactionFormModel
with any other fixed part of the ID.
As a side note, no need to locate the element twice. You can do
WebElement checkbox = webDriver.findElement(By.id("idOfTheElement"));
if (!checkbox.isSelected()) {
checkbox.click();
}
Upvotes: 0