Tag Name Locator in Selenium
Tag Name Locator is one of the locator strategies provided by Selenium WebDriver for identifying web elements using their HTML tag name. Every HTML element is represented using a tag such as input, button, a, h1, p, div, table, or select. Selenium can use these tag names to locate elements on a web page.
Tag Name is especially useful when multiple elements share the same HTML tag and the automation script needs to retrieve a collection of elements using findElements(). It can also be used with findElement() when the tag uniquely identifies the required element.
JustAcademy includes locators and WebDriver element interaction as part of its Selenium automation training curriculum. You can explore the JustAcademy's Selenium Training Course and use the Register for Course Demo link for course-related information.
1. What is a Tag Name?
A tag name is the name of an HTML element used to define the structure and content of a web page. For example, an input field uses the <input> tag, a button uses the <button> tag, and a hyperlink uses the <a> tag.
<input type="text" name="username">
<button type="submit">Login</button>
<a href="/home">Home</a>
<p>Welcome to Selenium</p>
In this example, the tag names are input, button, a, and p.
2. What is Tag Name Locator in Selenium?
Tag Name Locator allows Selenium WebDriver to locate an HTML element by specifying its tag name.
The Selenium Java syntax is:
driver.findElement(By.tagName("tagName"));
For example:
driver.findElement(By.tagName("input"));
This statement searches the current web page for an element whose HTML tag is input.
3. Basic Syntax
By.tagName("tagName")
Example:
WebElement element = driver.findElement(By.tagName("button"));
Here Selenium searches for an HTML element with the button tag.
4. Why Use Tag Name Locator?
Tag Name Locator is useful when the HTML tag itself provides enough information to identify the element or when the automation script needs to retrieve multiple elements of the same type.
- It is simple to understand.
- It works with standard HTML tags.
- It is useful for locating groups of elements.
- It is commonly used with
findElements().
- It can be useful for counting elements.
- It can help retrieve all links, buttons, headings, paragraphs, images, or input fields.
5. Selenium Method Used with Tag Name
The main Selenium method used with Tag Name is findElement().
WebElement element = driver.findElement(By.tagName("input"));
To locate multiple elements, use findElements().
List<WebElement> elements = driver.findElements(By.tagName("input"));
6. Setting Up Selenium
The following imports are commonly required when using Tag Name Locator with Selenium Java.
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;
7. Complete Basic Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TagNameExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement heading = driver.findElement(By.tagName("h1"));
System.out.println(heading.getText());
driver.quit();
}
}
In this example, Selenium searches for the first h1 element on the page and retrieves its text.
8. HTML Example for Tag Name Locator
<html>
<body>
<h1>Login Page</h1>
<p>Enter your credentials</p>
<input type="text">
<button>Login</button>
</body>
</html>
Possible tag names in this page include:
| HTML Element | Tag Name |
| Heading | h1 |
| Paragraph | p |
| Input | input |
| Button | button |
9. Locate an Input Field Using Tag Name
If a page contains an input field, Selenium can locate it using the input tag.
WebElement input = driver.findElement(By.tagName("input"));
However, if multiple input fields exist, findElement() normally returns the first matching element. Therefore, Tag Name alone may not be sufficient to identify a particular input field.
10. Locate a Button Using Tag Name
WebElement button = driver.findElement(By.tagName("button"));
button.click();
This searches for the first button element and clicks it.
11. Locate a Heading Using Tag Name
WebElement heading = driver.findElement(By.tagName("h1"));
System.out.println(heading.getText());
This approach is useful when a page contains a unique heading.
12. Locate a Paragraph Using Tag Name
WebElement paragraph = driver.findElement(By.tagName("p"));
System.out.println(paragraph.getText());
This retrieves the text of the first paragraph element.
13. Locate a Link Using Tag Name
HTML hyperlinks generally use the a tag.
WebElement link = driver.findElement(By.tagName("a"));
link.click();
This finds the first anchor element on the page.
14. Tag Name with findElements()
findElements() is particularly useful with Tag Name Locator because a web page can contain many elements having the same tag.
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + links.size());
The above code collects all anchor elements on the page.
15. Find All Input Fields
List<WebElement> inputs = driver.findElements(By.tagName("input"));
System.out.println("Total input fields: " + inputs.size());
This is useful when testing forms containing multiple input controls.
16. Find All Buttons
List<WebElement> buttons = driver.findElements(By.tagName("button"));
System.out.println("Total buttons: " + buttons.size());
17. Find All Links
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
System.out.println(link.getText());
}
This retrieves the visible text of every anchor element.
18. Find All Headings
You can retrieve all elements having the same heading tag.
List<WebElement> headings = driver.findElements(By.tagName("h2"));
for (WebElement heading : headings) {
System.out.println(heading.getText());
}
19. Find All Images
Images commonly use the img tag.
List<WebElement> images = driver.findElements(By.tagName("img"));
System.out.println("Total images: " + images.size());
20. Find All Paragraphs
List<WebElement> paragraphs = driver.findElements(By.tagName("p"));
for (WebElement paragraph : paragraphs) {
System.out.println(paragraph.getText());
}
21. Tag Name vs ID Locator
| Feature | Tag Name | ID |
| Strategy | Uses HTML tag | Uses id attribute |
| Syntax | By.tagName("input") | By.id("username") |
| Uniqueness | Often not unique | Usually intended to be unique |
| Multiple elements | Very useful | Usually targets one element |
| Common use | Collections of elements | Specific element |
22. Tag Name vs Name Locator
| Feature | Tag Name | Name |
| Uses | HTML tag | name attribute |
| Example | By.tagName("input") | By.name("username") |
| Uniqueness | Usually low | Depends on HTML |
| Multiple matches | Common | Possible |
23. Tag Name vs Class Name
| Feature | Tag Name | Class Name |
| Uses | HTML tag | class attribute |
| Example | By.tagName("button") | By.className("login-btn") |
| Typical usage | Element type | Styling/group-based identification |
24. Tag Name vs CSS Selector
CSS Selector can also select elements by tag name.
driver.findElement(By.cssSelector("input"));
This is conceptually similar to:
driver.findElement(By.tagName("input"));
CSS selectors become more useful when additional attributes or relationships are required.
25. Tag Name vs XPath
XPath can locate elements using their tag names as well.
driver.findElement(By.xpath("//input"));
The equivalent Tag Name locator is:
driver.findElement(By.tagName("input"));
XPath provides significantly more expression capabilities when the element needs to be located using attributes, text, relationships, or DOM hierarchy.
26. Tag Name for Multiple Elements
The most practical use of Tag Name Locator is retrieving multiple elements with findElements().
List<WebElement> elements = driver.findElements(By.tagName("input"));
for (WebElement element : elements) {
System.out.println(element.getAttribute("type"));
}
27. Counting Elements Using Tag Name
int count = driver.findElements(By.tagName("input")).size();
System.out.println("Input count: " + count);
This can be used in validation and test automation.
28. Verify That a Page Contains Buttons
List<WebElement> buttons = driver.findElements(By.tagName("button"));
if (buttons.size() > 0) {
System.out.println("Buttons are available.");
} else {
System.out.println("No buttons found.");
}
29. Iterate Through All Links
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
System.out.println("Text: " + link.getText());
System.out.println("URL: " + link.getAttribute("href"));
}
30. Verify Link URLs
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String url = link.getAttribute("href");
System.out.println(url);
}
This can be useful for link validation scenarios.
31. Tag Name with getText()
WebElement element = driver.findElement(By.tagName("h1"));
String text = element.getText();
System.out.println(text);
32. Tag Name with getAttribute()
WebElement input = driver.findElement(By.tagName("input"));
String type = input.getAttribute("type");
System.out.println("Input type: " + type);
33. Tag Name with isDisplayed()
WebElement button = driver.findElement(By.tagName("button"));
if (button.isDisplayed()) {
System.out.println("Button is displayed.");
}
34. Tag Name with isEnabled()
WebElement button = driver.findElement(By.tagName("button"));
if (button.isEnabled()) {
System.out.println("Button is enabled.");
}
35. Tag Name with isSelected()
isSelected() is generally useful for selectable elements such as checkboxes and radio buttons.
WebElement radio = driver.findElement(By.tagName("input"));
if (radio.isSelected()) {
System.out.println("Element is selected.");
}
When a page contains several input elements, Tag Name alone may locate the wrong input, so a more specific locator should normally be used.
36. Tag Name for Checkboxes
Checkboxes commonly use the input tag.
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
if ("checkbox".equals(input.getAttribute("type"))) {
System.out.println("Checkbox found.");
}
}
37. Tag Name for Radio Buttons
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
if ("radio".equals(input.getAttribute("type"))) {
System.out.println("Radio button found.");
}
}
38. Tag Name for Text Fields
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
if ("text".equals(input.getAttribute("type"))) {
System.out.println("Text field found.");
}
}
39. Tag Name for Password Fields
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
if ("password".equals(input.getAttribute("type"))) {
System.out.println("Password field found.");
}
}
40. Tag Name for Submit Buttons
Some forms use input elements as submit controls.
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
if ("submit".equals(input.getAttribute("type"))) {
input.click();
}
}
41. Tag Name for Select Elements
The HTML select tag represents a standard dropdown.
WebElement dropdown = driver.findElement(By.tagName("select"));
For selecting options, Selenium's Select class can be used.
import org.openqa.selenium.support.ui.Select;
WebElement dropdown = driver.findElement(By.tagName("select"));
Select select = new Select(dropdown);
select.selectByVisibleText("India");
42. Tag Name for Option Elements
Dropdown options are commonly represented using the option tag.
List<WebElement> options = driver.findElements(By.tagName("option"));
for (WebElement option : options) {
System.out.println(option.getText());
}
43. Tag Name for Table Rows
HTML tables commonly use the tr tag for rows.
List<WebElement> rows = driver.findElements(By.tagName("tr"));
System.out.println("Total rows: " + rows.size());
44. Tag Name for Table Cells
Table cells normally use the td tag.
List<WebElement> cells = driver.findElements(By.tagName("td"));
for (WebElement cell : cells) {
System.out.println(cell.getText());
}
45. Tag Name for Table Headers
Table header cells use the th tag.
List<WebElement> headers = driver.findElements(By.tagName("th"));
for (WebElement header : headers) {
System.out.println(header.getText());
}
46. Tag Name for List Items
HTML unordered and ordered lists commonly contain li elements.
List<WebElement> items = driver.findElements(By.tagName("li"));
for (WebElement item : items) {
System.out.println(item.getText());
}
47. Tag Name for Navigation Menus
Navigation menus often contain multiple anchor elements. Tag Name can retrieve all links.
List<WebElement> menuLinks = driver.findElements(By.tagName("a"));
for (WebElement link : menuLinks) {
System.out.println(link.getText());
}
48. Tag Name for Images
List<WebElement> images = driver.findElements(By.tagName("img"));
for (WebElement image : images) {
System.out.println(image.getAttribute("src"));
}
49. Tag Name and Dynamic Web Pages
Tag Name can work with dynamically generated pages, but the tag itself must remain suitable for identifying the desired element. If many elements share the same tag, additional filtering may be required.
List<WebElement> buttons = driver.findElements(By.tagName("button"));
for (WebElement button : buttons) {
System.out.println(button.getText());
}
50. Tag Name with Filtering
When Tag Name returns multiple elements, you can inspect attributes and text to identify the required element.
List<WebElement> buttons = driver.findElements(By.tagName("button"));
for (WebElement button : buttons) {
if ("Login".equals(button.getText())) {
button.click();
break;
}
}
51. Tag Name with Index
When multiple elements are returned, you can access an element by its list index.
List<WebElement> buttons = driver.findElements(By.tagName("button"));
WebElement secondButton = buttons.get(1);
secondButton.click();
Index-based selection should be used carefully because changes in page structure can change the order of elements.
52. Difference Between findElement() and findElements()
| Feature | findElement() | findElements() |
| Return type | WebElement | List<WebElement> |
| Multiple matches | Returns first matching element | Returns all matching elements |
| No match | Throws NoSuchElementException | Returns empty list |
| Typical use | Specific element | Collection of elements |
53. Common Problem with Tag Name Locator
The main limitation of Tag Name Locator is that HTML tags are frequently reused throughout a page.
driver.findElement(By.tagName("input"));
If a page has ten input elements, Selenium may return the first input rather than the input you actually need.
54. Better Approach for Multiple Similar Elements
When many elements share the same tag, use a more specific locator.
driver.findElement(By.id("username"));
Or:
driver.findElement(By.name("username"));
Or:
driver.findElement(By.cssSelector("input[name='username']"));
55. Tag Name with CSS Selector for Better Precision
CSS Selector can combine the tag name with attributes.
driver.findElement(By.cssSelector("input[type='email']"));
This is more specific than:
driver.findElement(By.tagName("input"));
56. Tag Name with XPath for Better Precision
driver.findElement(By.xpath("//input[@type='email']"));
XPath allows the tag name to be combined with attributes, text, and DOM relationships.
57. Tag Name in a Login Form
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
String type = input.getAttribute("type");
if ("text".equals(type)) {
input.sendKeys("admin");
}
if ("password".equals(type)) {
input.sendKeys("password123");
}
}
58. Tag Name in a Registration Form
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
String type = input.getAttribute("type");
System.out.println("Input type: " + type);
}
59. Tag Name in an E-Commerce Page
Tag Name can be useful for retrieving product links, buttons, images, and other groups of elements.
List<WebElement> productLinks = driver.findElements(By.tagName("a"));
for (WebElement link : productLinks) {
System.out.println(link.getText());
}
60. Tag Name in a Product Table
List<WebElement> rows = driver.findElements(By.tagName("tr"));
for (WebElement row : rows) {
System.out.println(row.getText());
}
61. Tag Name in a Navigation Bar
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
if (link.isDisplayed()) {
System.out.println(link.getText());
}
}
62. Tag Name in a Form Validation
You can count input fields and verify that the form contains the expected number of controls.
List<WebElement> inputs = driver.findElements(By.tagName("input"));
int actualCount = inputs.size();
System.out.println("Input count: " + actualCount);
63. Explicit Wait with Tag Name
For dynamic applications, an explicit wait can be combined with a Tag Name locator.
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.tagName("button"))
);
button.click();
64. Wait for a Button to Become Clickable
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(
ExpectedConditions.elementToBeClickable(By.tagName("button"))
);
button.click();
65. Common Exceptions with Tag Name
| Exception | Possible Cause |
| NoSuchElementException | No matching element exists |
| ElementNotInteractableException | Element exists but cannot currently be interacted with |
| ElementClickInterceptedException | Another element blocks the click |
| StaleElementReferenceException | Element was replaced or DOM changed |
| TimeoutException | Explicit wait condition was not satisfied |
66. Handling NoSuchElementException
try {
WebElement button = driver.findElement(By.tagName("button"));
button.click();
} catch (org.openqa.selenium.NoSuchElementException e) {
System.out.println("Button was not found.");
}
67. Tag Name and Frames
If the required element exists inside an iframe, Selenium must first switch to that iframe before locating the element.
WebElement frame = driver.findElement(By.tagName("iframe"));
driver.switchTo().frame(frame);
WebElement input = driver.findElement(By.tagName("input"));
input.sendKeys("Hello");
driver.switchTo().defaultContent();
68. Tag Name and Nested Elements
When elements are nested, Tag Name can be used to retrieve elements inside a parent element.
WebElement form = driver.findElement(By.tagName("form"));
List<WebElement> inputs = form.findElements(By.tagName("input"));
System.out.println("Inputs inside form: " + inputs.size());
69. Searching Within a Parent Element
Searching within a parent WebElement can make Tag Name Locator more precise.
WebElement loginForm = driver.findElement(By.tagName("form"));
WebElement button = loginForm.findElement(By.tagName("button"));
button.click();
70. Tag Name with Multiple Forms
List<WebElement> forms = driver.findElements(By.tagName("form"));
System.out.println("Forms found: " + forms.size());
for (WebElement form : forms) {
List<WebElement> inputs = form.findElements(By.tagName("input"));
System.out.println("Inputs in form: " + inputs.size());
}
71. Tag Name and HTML Structure
Understanding HTML structure is important when using Tag Name Locator. The locator does not identify an element based on its text, id, class, or custom attributes. It identifies the element based on its tag.
<button id="loginButton" class="primary">Login</button>
The Tag Name for this element is:
button
The other information such as id, class, and visible text are separate properties.
72. Tag Name with HTML5 Elements
Tag Name Locator can be used with semantic HTML5 elements such as header, nav, main, section, article, aside, and footer.
WebElement header = driver.findElement(By.tagName("header"));
WebElement nav = driver.findElement(By.tagName("nav"));
WebElement main = driver.findElement(By.tagName("main"));
73. Tag Name for Semantic Elements
| Tag | Typical Purpose |
| header | Page or section header |
| nav | Navigation |
| main | Main content |
| section | Content section |
| article | Independent content |
| aside | Secondary content |
| footer | Footer content |
74. Tag Name and Case Sensitivity
HTML tag names are generally handled case-insensitively in HTML documents, but Selenium locator strings should normally be written using the standard lowercase HTML tag representation.
driver.findElement(By.tagName("input"));
75. Tag Name and Custom Web Components
Modern web applications may contain custom elements such as:
<user-profile></user-profile>
<app-header></app-header>
The custom element tag name can be used as a locator where appropriate.
driver.findElement(By.tagName("user-profile"));
76. Tag Name with Shadow DOM
For elements inside a Shadow DOM, simply using a page-level Tag Name Locator may not be sufficient. Selenium provides Shadow DOM support through shadow root APIs, and the automation script should first access the shadow root before locating elements inside it.
77. Tag Name and Dynamic Content
Dynamic applications can add or remove elements after page loading. Tag Name can still be used, but synchronization may be necessary.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(
ExpectedConditions.presenceOfElementLocated(By.tagName("button"))
);
78. Tag Name and AJAX Applications
AJAX-based applications may update the DOM without a complete page refresh. A wait condition can help Selenium locate elements after they become available.
WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("div")));
79. Tag Name in Page Object Model
Tag Name Locator can be used inside a Page Object Model class when the element type is stable and sufficiently specific.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class HomePage {
private WebDriver driver;
private By heading = By.tagName("h1");
public HomePage(WebDriver driver) {
this.driver = driver;
}
public String getHeading() {
return driver.findElement(heading).getText();
}
}
80. Reusable Method for Counting Elements
public int countElements(By locator) {
return driver.findElements(locator).size();
}
Example:
int buttonCount = countElements(By.tagName("button"));
System.out.println("Buttons: " + buttonCount);
81. Reusable Method for Printing Element Text
public void printElementTexts(By locator) {
List<WebElement> elements = driver.findElements(locator);
for (WebElement element : elements) {
System.out.println(element.getText());
}
}
82. TestNG Example Using Tag Name
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TagNameTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
driver.get("https://example.com");
}
@Test
public void verifyHeading() {
String heading = driver.findElement(By.tagName("h1")).getText();
Assert.assertFalse(heading.isEmpty());
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
83. Real-World Example: Validate Page Headings
List<WebElement> headings = driver.findElements(By.tagName("h2"));
Assert.assertTrue(headings.size() > 0, "No H2 headings found.");
for (WebElement heading : headings) {
System.out.println(heading.getText());
}
84. Real-World Example: Validate Navigation Links
List<WebElement> links = driver.findElements(By.tagName("a"));
Assert.assertTrue(links.size() > 0, "No links found.");
for (WebElement link : links) {
System.out.println(link.getText());
}
85. Real-World Example: Count Form Controls
List<WebElement> controls = driver.findElements(By.tagName("input"));
System.out.println("Total form controls: " + controls.size());
86. Real-World Example: Validate Buttons
List<WebElement> buttons = driver.findElements(By.tagName("button"));
for (WebElement button : buttons) {
System.out.println("Button: " + button.getText());
System.out.println("Displayed: " + button.isDisplayed());
System.out.println("Enabled: " + button.isEnabled());
}
87. Common Mistake: Assuming Tag Name Is Unique
A common beginner mistake is assuming that a tag name identifies one specific element.
driver.findElement(By.tagName("input"));
A page may contain many input elements, so this locator may not select the intended field.
88. Common Mistake: Using Tag Name for Every Element
Tag Name should not automatically be the first choice for every element. If an element has a reliable unique ID, Name, CSS selector, or another stable attribute, a more specific locator may be appropriate.
89. Common Mistake: Using Index Without Understanding DOM Order
List<WebElement> buttons = driver.findElements(By.tagName("button"));
buttons.get(2).click();
This depends on the third button remaining in the same position. If the page structure changes, the test may interact with another button.
90. Common Mistake: Ignoring Dynamic Content
Immediately locating a dynamically generated element may cause synchronization problems. Use appropriate waits when the application requires them.
91. Best Practices for Tag Name Locator
- Use Tag Name when the element type itself is useful.
- Use
findElements() when working with multiple elements.
- Use parent-child searching to narrow the scope when appropriate.
- Use stable attributes when Tag Name alone is ambiguous.
- Avoid unnecessary index-based selection.
- Use explicit waits for dynamic elements when required.
- Keep locators readable and maintainable.
- Prefer reliable locator strategies over fragile DOM assumptions.
92. When Should You Use Tag Name?
| Scenario | Tag Name Suitability |
| Count all links | Useful |
| Count all buttons | Useful |
| Find all input fields | Useful |
| Read all table rows | Useful |
| Read all list items | Useful |
| Locate a unique element | Can be useful |
| Locate one input among many inputs | Usually too broad |
| Locate element by text | Use another locator |
93. Tag Name Locator Advantages
- Simple syntax.
- Easy for beginners to understand.
- Useful for collections of elements.
- Useful for counting elements.
- Useful for validating page structure.
- Works with standard HTML elements.
- Can be combined with WebElement methods.
94. Tag Name Locator Limitations
- Many elements may share the same tag.
- It may not uniquely identify a specific element.
- It provides less precision than CSS Selector or XPath.
- Index-based selection can be fragile.
- Dynamic pages may require additional synchronization.
95. Tag Name Locator Interview Question
Q: What is Tag Name Locator in Selenium?
Tag Name Locator is a Selenium locator strategy that identifies web elements using their HTML tag name.
96. Interview Question: Syntax
Q: What is the syntax for Tag Name Locator?
driver.findElement(By.tagName("input"));
97. Interview Question: Multiple Elements
Q: How do you find all elements with the same tag?
List<WebElement> elements =
driver.findElements(By.tagName("input"));
98. Interview Question: findElement vs findElements
Q: Why is findElements() commonly used with Tag Name?
Because many HTML elements often share the same tag name. For example, a page can contain multiple links, buttons, input fields, rows, or list items.
99. Interview Question: Locate All Links
Q: How can you locate all links on a page?
List<WebElement> links =
driver.findElements(By.tagName("a"));
100. Interview Question: Locate All Images
List<WebElement> images =
driver.findElements(By.tagName("img"));
101. Interview Question: Locate Table Rows
List<WebElement> rows =
driver.findElements(By.tagName("tr"));
102. Interview Question: Tag Name vs XPath
Q: Can XPath perform the same basic tag selection?
Yes. For example:
By.tagName("input")
can be conceptually represented using:
By.xpath("//input")
XPath can then extend the expression with attributes, text, and DOM relationships.
103. Interview Question: Tag Name vs CSS
Q: Can CSS Selector select elements by tag name?
Yes.
By.cssSelector("input")
CSS selectors can additionally combine tag names with classes, IDs, attributes, and other CSS selector capabilities.
104. Interview Question: First Matching Element
Q: What happens when findElement() finds multiple elements?
findElement() returns the first matching element found by the locator strategy.
105. Interview Question: No Matching Element
Q: What happens when findElement() cannot find a matching element?
Selenium throws a NoSuchElementException.
106. Interview Question: No Matching Elements with findElements()
Q: What does findElements() return when there are no matches?
It returns an empty list rather than throwing NoSuchElementException for the absence of matching elements.
107. Practical Exercise 1: Count All Links
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + links.size());
108. Practical Exercise 2: Count All Buttons
List<WebElement> buttons = driver.findElements(By.tagName("button"));
System.out.println("Total buttons: " + buttons.size());
109. Practical Exercise 3: Print All Headings
List<WebElement> headings = driver.findElements(By.tagName("h2"));
for (WebElement heading : headings) {
System.out.println(heading.getText());
}
110. Practical Exercise 4: Print All List Items
List<WebElement> items = driver.findElements(By.tagName("li"));
for (WebElement item : items) {
System.out.println(item.getText());
}
111. Practical Exercise 5: Find All Form Inputs
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
System.out.println(
input.getAttribute("type")
);
}
112. Practical Exercise 6: Find All Buttons and Their Text
List<WebElement> buttons = driver.findElements(By.tagName("button"));
for (WebElement button : buttons) {
System.out.println(button.getText());
}
113. Practical Exercise 7: Validate Page Structure
Assert.assertTrue(
driver.findElements(By.tagName("header")).size() > 0
);
Assert.assertTrue(
driver.findElements(By.tagName("main")).size() > 0
);
Assert.assertTrue(
driver.findElements(By.tagName("footer")).size() > 0
);
114. Practical Project: Web Page Element Analyzer
A useful beginner Selenium project is a Web Page Element Analyzer that counts and displays different HTML elements on a page.
System.out.println("Links: " +
driver.findElements(By.tagName("a")).size());
System.out.println("Images: " +
driver.findElements(By.tagName("img")).size());
System.out.println("Inputs: " +
driver.findElements(By.tagName("input")).size());
System.out.println("Buttons: " +
driver.findElements(By.tagName("button")).size());
System.out.println("Paragraphs: " +
driver.findElements(By.tagName("p")).size());
System.out.println("Headings: " +
driver.findElements(By.tagName("h1")).size());
115. Practical Project: Form Analyzer
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
String type = input.getAttribute("type");
String name = input.getAttribute("name");
System.out.println(
"Type: " + type + ", Name: " + name
);
}
116. Practical Project: Link Analyzer
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
System.out.println("Text: " + link.getText());
System.out.println("URL: " + link.getAttribute("href"));
}
117. Practical Project: Table Analyzer
List<WebElement> rows = driver.findElements(By.tagName("tr"));
for (WebElement row : rows) {
List<WebElement> cells = row.findElements(By.tagName("td"));
for (WebElement cell : cells) {
System.out.print(cell.getText() + " | ");
}
System.out.println();
}
118. Tag Name Locator Best-Practice Checklist
- Understand the HTML structure before selecting the locator.
- Use lowercase standard tag names.
- Use
findElements() for collections.
- Use Tag Name when the element type is relevant.
- Do not assume the tag name is unique.
- Use attributes or another locator when additional precision is required.
- Avoid unnecessary list indexes.
- Use explicit waits for dynamic elements.
- Keep locators maintainable.
- Validate the locator in browser developer tools when necessary.
119. Quick Reference Table
| HTML Element | Tag Name | Selenium Example |
| Text Input | input | By.tagName("input") |
| Button | button | By.tagName("button") |
| Link | a | By.tagName("a") |
| Image | img | By.tagName("img") |
| Heading | h1 | By.tagName("h1") |
| Paragraph | p | By.tagName("p") |
| Table Row | tr | By.tagName("tr") |
| Table Cell | td | By.tagName("td") |
| List Item | li | By.tagName("li") |
| Dropdown | select | By.tagName("select") |
| Dropdown Option | option | By.tagName("option") |
| Form | form | By.tagName("form") |
120. Tag Name Locator Learning Flow
Understand HTML
↓
Identify Element Tag
↓
Choose Tag Name
↓
Use By.tagName()
↓
Use findElement() or findElements()
↓
Interact with WebElement
↓
Validate Result
↓
Add Waits if Required
↓
Create Maintainable Automation Test
121. Summary of Tag Name Locator
Tag Name Locator identifies web elements based on their HTML tag name. It is simple and particularly useful when the automation test needs to retrieve multiple elements of the same type. Common examples include finding all links using a, all input fields using input, all buttons using button, all rows using tr, and all list items using li.
The most important limitation is that tag names are frequently shared by many elements. Therefore, Tag Name should be combined with a more specific locator or additional filtering whenever a particular element must be identified.
122. Final Example
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 FinalTagNameExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement heading =
driver.findElement(By.tagName("h1"));
System.out.println("Heading: " + heading.getText());
List<WebElement> links =
driver.findElements(By.tagName("a"));
System.out.println("Total Links: " + links.size());
List<WebElement> images =
driver.findElements(By.tagName("img"));
System.out.println("Total Images: " + images.size());
driver.quit();
}
}
123. Key Points to Remember
- Tag Name Locator: Identifies elements using their HTML tag name.
- Syntax:
By.tagName("tagName")
- Single element: Use
findElement().
- Multiple elements: Use
findElements().
- Common tags:
input, button, a, img, p, h1, tr, td, li.
- Main advantage: Simple and useful for collections.
- Main limitation: Tag names are often not unique.
- Better precision: Use ID, Name, CSS Selector, XPath, or another stable locator when necessary.
- Dynamic pages: Use appropriate waits when elements are loaded asynchronously.
124. Conclusion
Tag Name is an important Selenium locator strategy for identifying web elements through their HTML tag names. It is especially useful when working with groups of similar elements such as links, buttons, inputs, table rows, images, headings, and list items.
For beginner Selenium automation, understanding Tag Name helps build a strong foundation in WebElement identification. As automation scenarios become more complex, Tag Name can be combined with parent-element searches, WebElement attributes, CSS Selectors, XPath, and synchronization techniques to create more precise and maintainable tests.
To learn more about Selenium automation testing, visit the JustAcademy's Selenium Training Course.
For course demonstration and enrollment-related information, visit Register for Course Demo.