Clicking a Button By ID, Name, Image, and Javascript
Learn how to find and click web buttons using locators through Selenium.
We'll cover the following
Click a button by ID
As always, the best way to identify a button is by using IDs.
driver.findElement(By.id("choose_selenium_btn")).click();
This applies to all the controls if their IDs are present.
For testers who are working alongside the programmers, the best option is to ask programmers to add IDs. This is better than spending hours and hours finding a way to identify the web control. It requires very little effort from programmers to add the IDs.
Click a button by Name
For an input button, we can use a generic attribute name
to locate a control as:
driver.findElement(By.name("submit_action")).click();
Click a button by Image
Another type of button is the image button. This is basically an image that works exactly like a submit button in a form.
<input type="image" src="images/button_go.jpg"/>
Beside using IDs, the button can also be identified by using src
attribute as well.
driver.findElement(By.xpath("//input[contains(@src, 'button_go.jpg')]")).click();
Click a button via JavaScript
We can also invoke a button click via JavaScript. This comes in handy when normal approaches fail to click a button reliably in the browser.
the_btn = driver.findElement(By.id("searchBtn"));
driver.executeScript("arguments[0].click();", the_btn);
In addition to this, JavaScript can also be used to control the state of a button. For example, the below script will disable the searchBtn
.
driver.executeScript("arguments[0].disabled = true;", the_btn);
Get hands-on with 1400+ tech skills courses.