Selenium WebDriver's By
class provides a tagName()
method to find elements by their HTML tag name. This is similar to the getElementsByTagName()
DOM method in JavaScript.
This is used when you want to locate elements using their tag name, for example, locating all <tr>
tags in a table.
In this recipe, we will briefly see how to use the tagName()
locator method.
Let's assume you have a single button element on a page. You can locate this button by using its tag in the following way:
WebElement loginButton = driver.findElement(By.tagName("button")); loginButton.click();
Take another example where we want to count how many rows are displayed in <table>
. We can do this in the following way:
WebElement table = driver.findElement(By.id("summaryTable")); List<WebElement> rows = table.findElements(By.tagName("tr")); assertEquals(10, rows.size());
18.188.115.155