Get Tag Name of Element

To get the tag name of a web element programmatically using Selenium in Java, use WebElement.getTagName() function.

We first find the web element by name, id, class name, etc., and then call the getTagName() function on this web element. getTagName() function returns a String object specifying the tag of this web element.

The following is a simple code snippet where we find an element with the name q and then get the tag name programmatically.

</>
Copy
WebElement searchBox = driver.findElement(By.name("q"));
String tagName = searchBox.getTagName();

Example

In the following program, we write Java code to find a web element with the name q, get its tag name, and print the tag name to console output.

Java Program

</>
Copy
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.time.Duration;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");  
    	WebDriver driver = new ChromeDriver();
        driver.get("https://google.com/ncr");
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));

        WebElement searchBox = driver.findElement(By.name("q"));
        String tagName = searchBox.getTagName();        
        System.out.println("Tag Name : " + tagName);

        driver.quit();
    }
}

Output

Tag Name : input