Selenium WebDriver interacts with the web elements on the web page by first locating the elements on the page and performing actions such as clicking, selecting, or entering any text to it.
Selenium WebDriver interface provides two methods findElement() and findElements() with which you can identify element(s) on the web page.
findElement() method is used to return the first matching element on the web page and findElements() method is used to identify the list of matching web elements within the web page.
What is findElement by Class in Selenium?
findElement() is a method which is used to locate a single web element on a web page. findElement() method can be used with various locators such as ID, Name, Class Name, XPath, TagName, LinkText, PartialLinkText, CSS to uniquely locate the web elements.
You can use the findElement() along with the By.className locator to locate an element using its class name.
Syntax of findElement by Class in Selenium
driver.findElement(By.className(“className_value”));
parameter “className_value” is the class name of the web element you want to locate.
The findElement method returns the first element that matches the given class name. And if there are multiple elements with the same class name, only the first element will be returned.
Note: Avoid using findElement() to locate non-existent elements. Instead, use findElements(By) and verify that the returned list has zero length.
Selenium By.class() Method
Selenium WebDriver provides various ways to locate web elements on a web page, out of which one is by using class name/ property. In HTML, the class attribute is used to assign one or more class names to an HTML element.
These class names are primarily used for styling, JavaScript interactions and DOM manipulation. When an element has more than one class name, it is separated by spaces
In the above example, if you need to locate the “Get started free” button, out of so many class names, you may use the “get-started-hero” class name.
driver.findElement(By.className("get-started-hero "));
How to Find Element by Class in Selenium
Follow the steps below to find an element by its class name using the By.className() method
Prerequisites
Step 1 Install Java Development Kit (JDK)
- Before installing Selenium, make sure to download Java from the Oracle Download page.
- Set the JAVA_HOME path variable in System’s environment variables.
- Verify Java is installed correctly by opening the command prompt and running the command
java -version
Step 2. Set Up the IDE: Set up and use Eclipse or IntelliJ as the editor for writing Java code.
Step 3. Selenium WebDriver: Add Selenium Jars in the project or add Selenium Java dependencies if you are using a Maven project
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.27.0</version> <!-- Choose the latest version --> </dependency>
Code Example
Once the pre-requisites are in place, write the test script to find element by class in Selenium Java.
public class ByClassName { WebDriver driver; @Test public void clickGetStartedFree() throws IOException { driver = new ChromeDriver(); driver.get("https://www.browserstack.com"); try { WebElement getStartedFree= driver.findElement(By.className("get-started-hero")); getStartedFree.click(); Assert.assertTrue(driver.getCurrentUrl().contains("sign_up")); }catch (Exception e) { System.out.println("Assert failed: "+e.getStackTrace()); } driver.quit(); } }
Code Explanation:
- The findElement(By.className(“get-started-hero”)) locates the Get Started element with the class name “get-started-hero”.
- After the element is located, the button is clicked.
- Finally, an assert is performed to verify the page URL.
When to use Finding Element by Class in Selenium
Finding an element by class can be helpful in different scenarios especially when the class name is unique. Following are some scenarios when you should use By.className() to locate elements.
1. When the class name is unique: If any web element has a unique class name, it is best to locate that element using class name instead of using any other locator.
For example:
<button class="submit-btn">Submit</button>
You can locate submit button using class name as follows:
driver.findElement(By.className("submit-btn"))
2. When finding multiple elements with the same class name: When there are multiple elements on the web page which have the same class name, you can use By.className() that will locate the first matching web element.
If you need to find all the elements with the same class name, you can use findElements() methods instead of findElement() that will return a list of matching elements.
For example:
<button class="btn">Cancel</button> <button class=" btn">Submit</button> <button class=" btn">Reset</button>
You can locate all the buttons using class name and store it in a list as follows:
List<WebElement> buttons=driver.findElements(By.className("btn"));
Later, you may iterate over this list to perform required action.
3. Using in combination with other locators: Sometimes, some elements cannot be located by just one locator mechanism. In such cases, you may want to combine multiple locators to locate that specific element, like combining class name with other locator.
For example:
<button class="btn">Cancel</button> <button class="btn">Submit</button> <button class="btn">Reset</button>
Here, all the button elements have the class name as “btn”, and if you need to interact with the submit button you can use XPATH to filter the element by its text and combine it with the class name to make the search more specific.
driver.findElement(By.xpath("//button[contains(@class, ‘btn’) and text()='Submit']"))
Benefits of Finding Element by Class in Selenium
Finding element by class has several benefits, some of which are listed below:
- Speed: When the web page structure is simple and well maintained, finding web elements in Selenium using by class can be quicker as compared to using XPATH or CSS selectors. Selenium locates element by class names more efficiently because class names are usually unique.
- Less maintenance: As class names are more stable and less likely to change, using By class method for finding such elements requires less maintenance. It helps avoid the fragility of absolute XPath or other selectors, which can break due to small changes in the HTML structure.
- Simple and easy to read: Using by class name is straightforward and easy to understand. Its syntax is much easier and clearer as compared to XPath or CSS selectors. Due to its ease, beginners may find it very comfortable to use it.
- Cross browser compatibility: Class name selectors mostly work across all major browsers which are supported by Selenium. Inconsistencies in behaviour between different browsers can be avoided by using class names whenever you want your script to run in a cross browser environment.
Challenges of using findElement by Class in Selenium with Solution
Here are the key challenges of using findElement by Class in Selenium with Solution:
1. Non-unique class names: Many elements on a webpage may share the same class name, leading to ambiguity and selecting the wrong element.
Solution: Use a more specific class or combine it with other locators like XPath or CSS selectors to ensure uniqueness.
2. Dynamic class names: Websites often use dynamically generated class names that change frequently, which can break the locator.
Solution: Use more stable attributes like id, name, or consider using XPath with contains() to match partial or dynamic class names.
3. Multiple classes: Some elements may have multiple classes, making it harder to target a specific one.
Solution: Use CSS selectors with exact class matching (like, .class1.class2) or XPath to specify the class more accurately.
4. Hidden or non-interactive elements: Elements with certain classes might not be visible or interactable, leading to errors.
Solution: Ensure that the element is visible and interactable before performing actions, using WebDriverWait or other wait mechanisms.
By using a combination of strategies like XPath or CSS selectors, dynamic elements can be handled more effectively in Selenium.
Best Practices when Finding Element by Class in Selenium
Here are the key best practices when finding element by Class in Selenium:
1. Use unique class names: Elements that have unique and descriptive class names should always be preferred instead of generic class names. This will lower the risk of selecting the wrong element.
For example, consider below HTML code:
<button class="btn">Cancel</button> <button class="btn submit">Submit</button> <button class="btn">Reset</button>
All the buttons have a common class value as “btn“ and only the submit button has an additional class value as “submit”. If you wish to select submit button you should use locator as
driver.findElement(By.className(“submit”)).
If you use a common class value as driver.findElement(By.className(“btn”)), cancel button would be located instead of submit button.
2. Use class names for static elements: Static elements are the ones that do not change often and whose attributes remain the same such as form field elements and navigation links. Class names can be used to locate such static elements as their chance of getting modified is very less.
3. Avoid using dynamic class names: Dynamic elements are the ones that update its attributes very often due to AJAX calls, or JavaScript functioning on the web page. Avoid using class names for such dynamic elements and instead use XPath or CSS selectors.
For example, Consider the below HTML button with class value as “btn_123”
<button class="btn_123">Cancel</button>
Here, if the class value keeps on changing on every page load, using driver.findElement(By.className(“btn_123”)) would lead to NoSuchElementException. You can use XPath in this case with the contains function.
driver.findElement(By.xpath("//button[contains(@class, 'btn_')]"))
4. Use explicit waits: Implicit waits are the global waits which may lead to unpredictable results and therefore, explicit waits should be used which allows you to wait for the specific conditions before proceeding for any action to avoid any exception.
If Selenium tries to interact with an element that is not completely loaded, it may throw an ElementNotInteractableException. Therefore, to avoid such exceptions it is always a good practice to use explicit waits wherever possible.
5. Use combination of class names with other attributes: Sometimes, class name alone can be insufficient to locate unique elements on the web page. Since class names can be shared among multiple elements and may change, use them judiciously, primarily in conjunction with other attributes. Consider combining class name with other attributes such as ID, name or text to create more robust and stable locators.
Conclusion
FindElement by class is a simple and efficient way to locate web elements when the class name is unique. You would have a solid foundation for automating web applications by mastering how to find elements by class in Selenium.
Selenium is popular for creating robust and stable automation scripts in website test automation.
BrowserStack Automate is the best Cloud-based platform, which testers could use to run their tests on 3500+ devices, browsers and platforms! If you are eager to start your web automation journey, try exploring BrowserStack Automate capabilities to help you in your automation journey by signing in today!