How to Locate Elements Using By.tagName() in Selenium WebDriver

The By.tagName() locator in Selenium is used to identify web elements by their HTML tag name. This is especially useful when you want to select elements like <input>, <button>, <a>, or <div> when no other unique attributes are available.

🔎 What is a Tag Name?

A tag name refers to the name of the HTML element, such as input, button, a, div, etc.

<input type="text" name="username" />
<button type="submit">Login</button>
<a href="/home">Home</a>

✅ When to Use By.tagName()?

📌 Syntax in Java

driver.findElement(By.tagName("tagname"));

To fetch multiple elements of the same tag:

driver.findElements(By.tagName("tagname"));

💻 Example: Fetch All Links on a Page

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;

public class LinksExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("https://example.com");

        // Get all anchor (link) elements
        List<WebElement> allLinks = driver.findElements(By.tagName("a"));

        System.out.println("Total links found: " + allLinks.size());

        for (WebElement link : allLinks) {
            System.out.println(link.getText() + " - " + link.getAttribute("href"));
        }

        driver.quit();
    }
}

🧪 Example: Access Table Rows

If you want to get all rows from a table:

WebElement table = driver.findElement(By.id("userTable"));
List<WebElement> rows = table.findElements(By.tagName("tr"));

for (WebElement row : rows) {
    System.out.println(row.getText());
}

✅ Best Practices

⚠️ Common Mistakes

Mistake How to Avoid
Using findElement() when multiple elements exist Use findElements() to avoid missing results
Accessing tag without scoping inside a container Use parent element’s findElements() to restrict search area
Assuming tags are unique Verify with browser inspection or DevTools

📚 Summary

  • By.tagName() allows locating elements using standard HTML tags.
  • Best for selecting all elements of a type like <a>, <input>, <tr>, etc.
  • Use findElements() when expecting multiple results.

🚀 Keep Learning

Explore other locators in Selenium:

🤖
PrepCampusPlus AI Tutor
Scroll to Top