We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Verify the HTML tag of an element to ensure you found the right one.
getTagName() helps you confirm what type of HTML element you actually found.
"input", "button", "a", "div").WebElement as a String.<input name="email" />, getTagName() returns "input".//button[...] or //a[...] and you want to assert the tag.name AttributeDon't mix these up:
input, button, a, div, etc. Returned by getTagName().name Attribute — A specific attribute on some elements, e.g. name="emailAddress". Accessed via getAttribute("name").Key idea: Tag name = element type. name attribute = metadata on that element.
Imagine a small "tag guessing" area with three elements that look similar but are different HTML types.
You see three clickable blocks:
Under the hood (for you as a tester):
element-1 is a button element.element-2 is an anchor/link element.element-3 is a div element.Click each element and see what tag type it really is. Then use getTagName() in Selenium to verify!
getTagName() returns and confirm your guesses.The goal: Connect what you see in the UI with what Selenium actually sees in the DOM.
123456789101112WebElement el1 = driver.findElement(By.id("element-1"));
System.out.println("Element 1 is a: " + el1.getTagName());
WebElement el2 = driver.findElement(By.id("element-2"));
System.out.println("Element 2 is a: " + el2.getTagName());
WebElement el3 = driver.findElement(By.id("element-3"));
System.out.println("Element 3 is a: " + el3.getTagName());
if (!"button".equals(el1.getTagName())) {
System.out.println("Error: Element 1 should be a button!");
}id="element-1" (the one that looks like a button).el1 (e.g. "button").Use getTagName() when debugging "Why is my locator not working?" It quickly tells you if you targeted the wrong type of element.
Remember: getTagName() returns lowercase (e.g. "button", not "BUTTON"), so compare with lowercase strings.
When writing XPath or CSS that depends on the tag (//button[...], a[href*='login']), validate the element type with getTagName() to catch UI changes early.