A Beginner’s Guide to using findElement by Class in Selenium

On This Page What is findElement by Class in Selenium?February 11, 2026 · 9 min read · Tool Comparison

A Beginner ’ s Guide to using findElement by Class in Selenium

interacts with the web constituent 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 methodswith which you can identify element (s) on the web page.

findElement () method is used to return the maiden matching element on the web page and findElements () method is used to identify the list of matching web factor within the web page.

What is findElement by Class in Selenium?

is a method which is expend to locate a single web component on a web page. findElement () method can be used with various locator such as ID, Name, Class Name, XPath, TagName, LinkText, PartialLinkText, CSS to uniquely place the web elements.

You can use the findElement () along with the By.className locator to locate an element utilise its class name.

Syntax of findElement by Class in Selenium

driver.findElement (By.className (“ className_value ”));

argument “className_value” is the class name of the web element you need to locate.

The findElement method returns the first element that matches the afford class name. And if there are multiple elements with the same class gens, only the initiative element will be regress.

Note: Avoid use findElement () to locate non-existent elements. Instead, use findElements (By) and verify that the returned list has zero duration.

Selenium By.class () Method

Selenium WebDriver cater 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 apply to assign one or more class name to an HTML element.

These class names are mainly used for styling, JavaScript interactions and DOM use. When an element has more than one class name, it is distinguish by spaces

In the above example, if you need to locate the “Get started free” button, out of so many grade 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 measure below to find an element by its stratum gens using theBy.className () method

Prerequisites

Step 1 Install Java Development Kit (JDK)

  • Before installing Selenium, do sure to download Java from the OracleDownload page.
  • Set the JAVA_HOME path variable in System ’ s environment variables.
  • Verify Java is instal right by opening the bidding 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 codification.

Step 3. Selenium WebDriver: Add Selenium Jars in the project or add Selenium Java addiction if you are using a Maven undertaking

& lt; dependency & gt; & lt; groupId & gt; org.seleniumhq.selenium & lt; /groupId & gt; & lt; artifactId & gt; selenium-java & lt; /artifactId & gt; & lt; version & gt; 4.27.0 & lt; /version & gt; & lt;! -- Choose the latest version -- & gt; & lt; /dependency & gt;

Code Example

Once the pre-requisites are in property, publish the test script to happen element by class in Selenium Java.

public classByClassName {WebDriver driver; @ Testpublic voidclickGetStartedFree ()throwsIOException {driver =newChromeDriver (); 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 miscarry: `` +e.getStackTrace ());} driver.quit ();}}

Code Explanation:

  • The findElement (By.className (& # 8220; get-started-hero & # 8221;))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 ingredient by class can be helpful in different scenarios peculiarly 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 gens, it is best to locate that constituent using stratum gens instead of use any other locator.

For example:

& lt; button & gt; Submit & lt; /button & gt;

You can site submit button using class gens as follows:

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

driver.findElement (By.className (`` submit-btn ''))

2. When discover multiple factor with the same class name: When there are multiple factor on the web page which feature the same class name, you can use By.className () that will place the first matching web element.

If you need to find all the elements with the like family gens, you can usefindElements ()methods alternatively offindElement ()that will revert a list of matching elements.

For example:

& lt; button & gt; Cancel & lt; /button & gt; & lt; button & gt; Submit & lt; /button & gt; & lt; button & gt; Reset & lt; /button & gt;

You can place all the buttons using class name and stock it in a list as follows:

List & lt; WebElement & gt; buttons=driver.findElements (By.className("btn"));

Later, you may retell over this tilt to perform ask activity.

3. Using in combination with other locators: Sometimes, some elements can not be place by just one locator mechanism. In such cases, you may want to combine multiple locater to locate that specific element, like combining class name with other locator.

For example:

& lt; button & gt; Cancel & lt; /button & gt; & lt; button & gt; Submit & lt; /button & gt; & lt; button & gt; Reset & lt; /button & gt;

Here, all the button elements have the form 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 compound it with the class name to get the search more specific.

driver.findElement (By.xpath(`` //button [contains (@ class, ‘ btn ’) and text () ='Submit '] ''))

Benefits of Finding Element by Class in Selenium

Finding factor by grade has respective benefits, some of which are name below:

  1. Speed: When the web page construction is elementary and well maintained, finding web elements in Selenium habituate by class can be quicker as compared to use XPATH or CSS selectors. Selenium locates element by class name more expeditiously because class names are usually alone.
  2. Less maintenance: As category names are more stable and less likely to change, apply By grade method for notice such factor requires less maintenance. It helps avoid the fragility of sheer XPath or other picker, which can break due to small changes in the HTML structure.
  3. Simple and easy to read: Using by class name is straightforward and easy to understand. Its syntax is much easier and clearer as liken to XPath or CSS chooser. Due to its ease, beginners may happen it really comfy to use it.
  4. : Class name chooser mostly work across all major browsers which are back by Selenium. Inconsistencies in behaviour between different browsers can be avoided by using class names whenever you desire your script to run in a cross browser environment.

Challenges of apply findElement by Class in Selenium with Solution

Here are the key challenge 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 equivocalness and choose the wrong element.

Solution:Use a more specific class or combine it with other locators like XPath or CSS picker to ensure singularity.

2. Dynamic class names: Websites often use dynamically generated class names that modify frequently, which can interrupt the locator.

Solution:Use more stable property likeid, name, or take using XPath withcontains ()to pair partial or dynamic class name.

3. Multiple classes: Some elements may have multiple classes, do it harder to target a specific one.

Solution:Use CSS selectors with precise course matching (like,.class1.class2) or XPath to specify the class more accurately.

4. Hidden or non-interactive elements: Elements with sure category might not be visible or interactable, leading to errors.

Solution:Ensure that the element is visible and interactable before performing actions, usingWebDriverWaitor other wait mechanisms.

By expend 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 component by Class in Selenium:

1. Use unique class name: Elements that have unique and descriptive stratum names should always be preferred rather of generic class names. This will lower the risk of select the incorrect element.

For instance, consider below HTML codification:

& lt; button & gt; Cancel & lt; /button & gt; & lt; button & gt; Submit & lt; /button & gt; & lt; button & gt; Reset & lt; /button & gt;

All the button feature a common stratum value as “btn“ and only the submit push 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 mutual class value asdriver.findElement (By.className (“ btn ”)), cancel button would be located rather of submit push.

2. Use class names for stable elements: Unchanging elements are the 1 that do not change often and whose dimension remain the same such as form battleground elements and navigation links. Class names can be used to locate such static factor as their chance of getting alter is very less.

3. Avoid using dynamical class name: Dynamic component are the single that update its attribute very ofttimes due to AJAX ring, or JavaScript function on the web page. Avoid using family name for such dynamic elements and instead use XPath or CSS selectors.

For exemplar, Consider the below HTML button with family value as “ btn_123 ”

& lt; button & gt; Cancel & lt; /button & gt;

Here, if the class value keeps on changing on every page freight, usingdriver.findElement (By.className (“ btn_123 ”))would lead to. 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 postponement which may lead to unpredictable results and therefore, explicit waits should be use which allows you to wait for the specific weather before proceeding for any action to avoid any exception.

If Selenium tries to interact with an element that is not altogether loaded, it may throw an. Therefore, to avoid such exceptions it is ever a good drill to use explicit waits wherever possible.

Read More:

5. Use combination of category names with early attribute: Sometimes, form name unaccompanied can be insufficient to locate alone component on the web page. Since class names can be shared among multiple elements and may alter, use them judiciously, primarily in conjunction with other attribute. Consider combining class name with early attributes such as ID, name or text to create more robust and stable locater.

Conclusion

FindElement by form is a uncomplicated and effective way to locate web elements when the class name is unique. You would hold a solid foundation for automating web applications by mastering how to find elements by class in Selenium.

is popular for create robust and stable automation scripts in website trial automation.

is the good Cloud-based platform, which examiner could use to run their tests on 3500+ devices, browser and platforms! If you are eager to get your web automation journeying, try exploring BrowserStack Automate capabilities to help you in your mechanization journey by signing in today!

Tags
70,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free