Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud
  • Home
  • /
  • Blog
  • /
  • How to Find Element by Text in Selenium
Selenium JavaAutomationTutorial

How to Find Element by Text in Selenium

Learn how to findElement() by text in Selenium for dynamic IDs and Classes. Overcome challenges, enhance automation testing, and gain practical insights.

Author

Vipul Gupta

January 13, 2026

Locating WebElements precisely is essential for reliable Selenium testing. One commonly used technique is to find elements by text in Selenium, which helps identify elements based on their visible text, especially when other attributes aren’t unique or consistent.

Overview

Why Use Selenium to Find Element by Text?

Locating elements by text in Selenium is essential for automating interactions with web elements, particularly when IDs or classes are dynamic. It enables precise targeting of elements based on their visible text content, ensuring that your test scripts can handle unpredictable changes in element identifiers.

  • Handles Dynamic Elements: Useful when dealing with dynamic IDs or classes, making it easier to locate elements with varying attributes.
  • Text-Based Selection: Allows locating elements based on visible text, which is often more reliable for dynamic content than static attributes.
  • Improves Automation Efficiency: Simplifies element interaction without the need for complex or unique identifiers.

Methods to Find Element by Text in Selenium

Selenium provides various methods to locate elements by text using XPath. The text() and contains() methods are most commonly used to perform exact or partial matches for visible text in elements:

  • text(): Finds an element with an exact match of the text content. Example: driver.findElement(By.xpath("//a[text()='Submit']"));
  • contains(): Locates elements based on a partial match of the text, allowing for more flexible element identification. Example: driver.findElement(By.xpath("//a[contains(text(), 'Submit')]"));

Using findElement() Method for Complete Text Match

The findElement() method can be used to locate an element with a complete match to its text. This is ideal when you need to interact with elements that have static and predictable visible text:

  • Example: Identifying and interacting with an element using its exact visible text. driver.findElement(By.xpath("//a[text()='Checkbox Demo']"));

Using findElement() Method for Partial Text Match

When you need to locate elements with partial text, the contains() method helps in selecting WebElements that contain a specific text string. This is especially useful when element text is dynamic or partially predictable:

  • Example: Finding all elements that contain the word "Table." driver.findElements(By.xpath("//a[contains(text(), 'Table')]"));

How to Use XPath for Text-Based Element Selection

XPath is a powerful locator strategy in Selenium, and it allows you to find elements based on their visible text. It can be used to locate both exact and partial matches for the text in a WebElement, providing flexibility in automated tests:

  • Exact Match: Use text() for locating elements with exact matches to the visible text.
  • Partial Match: Use contains() for flexible matching based on part of the text.

Selenium Test Execution in TestMu AI

To run Selenium tests on dynamic elements, you can leverage the TestMu AI platform. It provides cloud-based Selenium grid capabilities, allowing you to execute tests on different browser and OS combinations without managing infrastructure. This simplifies parallel testing and reduces the need for local setup:

  • Cloud Testing: Enables scalable testing across multiple environments using TestMu AI.
  • Parallel Execution: Run Selenium tests concurrently on multiple browsers and OS configurations for faster results.

What Is Find Element by Text in Selenium?

Find element by text in Selenium is a way to locate a WebElement based on its visible text content using the findElement() method. It is useful when attributes like ID or ClassName are dynamic or unreliable for identification.

XPath is typically used as the locator strategy, leveraging the text() method to find element by text in Selenium.

driver.findElement(By.xpath("//*[text()='Submit']"));

Methods to Find Element by Text in Selenium

To find element by text in Selenium, you can use the text() and contains() methods in your XPath with the findElement() method.

  • text(): This built-in method in Selenium is used with XPath to locate an element based on its exact text value:
  • WebElement ele = driver.findElement(By.xpath(“//[text()=’textvalue’]”))
    

You can also extract text from a web page and print it in the console using the getText() method.

  • contains(): It is another built-in method which is used with XPath. However, this is used when writing the locator based on a partial text match.
  • WebElement ele =driver.findElement(By.xpath(“//[contains(text(),’textvalue’)]”))
    

Using findElement() Method for Complete Text Match

To find element by text in Selenium for complete text match, you can use the findElement() method. Here’s an example:

Test Scenario:

  • Log in to the TestMu AI Selenium Playground.
  • Identify the WebElement for the Checkbox Demo link using the text() method.
  • Click on it and print the page header.

Typically, you might run Selenium scripts on a local grid setup. However, here we’ll execute the test script on an online Selenium Grid using TestMu AI. This allows us to run tests in parallel across various browser and OS combinations without managing any infrastructure.

To get started, check out this documentation on Selenium testing with TestMu AI.

Note

Note: Run Selenium tests across 3000+ real environments. Try TestMu AI Now!

Step 1: Inspect the Element

  • Open the web page and right-click on the Checkbox Demo link.
  • Click Inspect to open the browser developer tools. In the Elements tab, you’ll see the HTML structure of the web page.
  • Use the anchor tag (a) and the text “Checkbox Demo” to find this element using XPath.
  • WebElement checkbox = driver.findElement(By.xpath("//a[text()='Checkbox Demo']"));
    
  • Open Eclipse IDE and create a Maven project named FindElementByText.
  • Inside the src folder, add a new package named test to hold all test files.
  • Create a BaseTest.java file to handle WebDriver setup, teardown, and TestMu AI cloud grid connection.
  • Update your pom.xml file with Selenium and TestNG dependencies.
  • <project xmlns="http://maven.apache.org/POM/4.0.0"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>FindElementByText</groupId>
       <artifactId>FindElementByText</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <build>
           <sourceDirectory>src</sourceDirectory>
           <plugins>
               <plugin>
                   <artifactId>maven-compiler-plugin</artifactId>
                   <version>3.8.1</version>
                   <configuration>
                       <release>17</release>
                   </configuration>
               </plugin>
           </plugins>
       </build>
       <dependencies>
           <dependency>
               <groupId>org.seleniumhq.selenium</groupId>
               <artifactId>selenium-java</artifactId>
               <version>4.16.1</version>
           </dependency>
           <dependency>
               <groupId>org.testng</groupId>
               <artifactId>testng</artifactId>
               <version>7.8.0</version>
               <scope>test</scope>
           </dependency>
       </dependencies>
    </project>
    
  • Create BaseTest.java file to set up and tear down the WebDriver, with connectivity to TestMu AI Selenium Grid.
  • public class BaseTest {
      
         public RemoteWebDriver driver = null;
    
    
         String username = System.getenv("LT_USERNAME") == null ? "<lambdatest_username>" : System.getenv("LT_USERNAME");
         String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "<lambdatest_accesskey>" : System.getenv("LT_ACCESS");
    
    
         @BeforeTest
         public void setup()
         {
             try
             {
                 ChromeOptions chromeOptions = new ChromeOptions();
                 chromeOptions.setPlatformName("Windows 10");
                 chromeOptions.setBrowserVersion("121.0");
                            
                 HashMap<String, Object> ltOptions = new HashMap<String, Object>();
    ltOptions.put("build", "Find Element by Text");
        		  ltOptions.put("project", "Find Element by Text in Selenium");
                 chromeOptions.setCapability("LT:Options", ltOptions);
    
    
                 driver = new RemoteWebDriver(
                         new URL("https://" + username + ":" + accessKey + "@hub.lambdatest.com/wd/hub"), chromeOptions);
             }
             catch (MalformedURLException e)
             {
                 e.printStackTrace();
             }
         }
    
    
         @AfterTest
         public void tearDown()
         {
             driver.quit();
         }
    }
    

You can get your TestMu AI Username and Access Key from your Account Settings > Password & Security to connect to the cloud grid for test execution. Alternatively, you can configure these as environment variables and directly fetch them in the test script.

After that, create a HashMap type variable to pass the additional browser capabilities required by the TestMu AI platform to support test execution on their cloud grid.

You can fetch the required browser capabilities for the TestMu AI platform by navigating to the Automation Capabilities Generator.

  • Create TestFindByTextForCompleteMatch.java file to perform the actual text match operation.
  • public class TestFindByTextForCompleteMatch extends BaseTest{
    
    
       @Test
       public void testFindElementByCompleteTextMatch()
       {
           System.out.println("Logging into Lambda Test Selenium Playground");
           driver.get("https://www.lambdatest.com/selenium-playground/");
           WebElement checkBoxDemoPage= driver.findElement(By.xpath("//a[text()='Checkbox Demo']"));
           checkBoxDemoPage.click();
           System.out.println("Clicked on the Checkbox Demo Page");
           WebElement header=driver.findElement(By.xpath("//h1"));
           System.out.println("The header of the page is:"+header.getText());
       }
    }
    

Using findElement() Method for Partial Text Match

  • Log in to the TestMu AI Selenium Playground.
  • Identify all the WebElements that have “Table” in their names.
  • Print the text of all such WebElements.
  • Right-click on any WebElement with “Table” in its name and select Inspect to open the browser developer tools.
  • In the Elements tab, use the anchor tag and partial text “Table” with XPath contains() method to locate these elements.

If there are more than one WebElement, you can use the findElements() method.

The findElements() method returns the list of WebElements that match the locator value, unlike the findElement() method, which returns only a single WebElement.

If there are no matching elements within the web page, the findElements() method returns an empty list.

    List tableOptions=driver.findElements(By.xpath(“//a[contains(text(),’Table’)”)
    
public class TestFindByTextForPartialMatch extends BaseTest {


   @Test
   public void testFindElementByPartialTextMatch() {


       System.out.println("Logging into Lambda Test Selenium Playground");
       driver.get("https://www.lambdatest.com/selenium-playground/");
       List tableOptions = driver.findElements(By.xpath("//a[contains(text(),'Table')]"));
       for (WebElement e : tableOptions) {
           System.out.println("The different options with table in name are:" + e.getText());
       }
   }
}

Using findElement() Method With text() and contains() Methods

  • Log in to the TestMu AI Selenium Playground.
  • Identify WebElements that have “Dynamic” in its name and click on it.
  • Print the header of the loaded page after the action.
WebElement element= driver.findElement(By.xpath(“//a[contains(text(),’Dynamic’)”)
public class TestFindByTextForSpecificContainingText extends BaseTest {
   @Test
   public void testFindElementBySpecificTextMatch() {
       System.out.println("Logging into Lambda Test Selenium Playground");
       driver.get("https://www.lambdatest.com/selenium-playground/");
       WebElement element = driver.findElement(By.xpath("//a[contains(text(),'Dynamic')]"));
       element.click();
       System.out.println("Clicked on the Dynamic Data Loading link");
       WebElement header = driver.findElement(By.xpath("//h1"));
       System.out.println("The header of the page is:" + header.getText());
   }


}

Conclusion

Author

Vipul Gupta is a Sr. Lead SDET at Zupee with over 9 years of experience in functional and automation testing. He has built 10+ automation projects from scratch covering web, API, and mobile applications. Vipul is skilled in Selenium, Appium, Rest Assured, Playwright, Java, Python, Pytest, BDD, TDD, Maven, Jenkins, TestNG, and JUnit. He has successfully led end-to-end QA efforts, including setting up teams from scratch and managing a 15-member QA team to ensure manual and automation testing run in parallel from day one. Vipul graduated in B.Tech CSE from CGC College of Engineering and is followed by 3,000+ QA and SDET professionals on LinkedIn, reflecting his strong influence in the testing community.

Close

Summarize with AI

ChatGPT IconPerplexity IconClaude AI IconGrok IconGoogle AI Icon

Frequently asked questions

Did you find this page helpful?

More Related Hubs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests