How to find an element using the attribute “HTML tag name” in Selenium?

We can find an element using the element tag name with Selenium webdriver with the help of locator tagname. To locate an element with tagname, we have to use the By.tagName method.

In the html code, a tagname is usually enclosed by <>, for example, an anchor tag <a> represents links on the page. An input tag represents text boxes, checkboxes or radio buttons. Let us look at the html code of an element and try to identify it with its tagname −

In the above image, the text – You are browsing the best resources for has the h4 tag.


WebElement e = driver. findElement(By.tagName("h4"));


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorTagName{
   public static void main(String[] args) {
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      // identify element with tag name
      WebElement n = driver.findElement(By.tagName("h4"));
      //obtain text on element
      String s = n.getText();
      System.out.println("Text on element is : " + s);


Updated on: 06-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started