O'Reilly logo

Selenium Testing Tools Cookbook by Unmesh Gundecha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Locating elements by tag name

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 comes in handy when you want to locate elements using their tag name. For example, locating all <tr> tags in a table and so on.

In this recipe, we will briefly see how to use the tagName locator method.

How to do it...

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:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required