We use findElement by tagName to locate the first HTML element on a web page by its tag name, like <button> or <input>.
0
0
findElement by tagName in Selenium Java
Introduction
When you want to click the first button on a page.
When you need to check the text inside the first paragraph (<p>) element.
When you want to find the first image (<img>) to verify it is displayed.
When you want to interact with the first input field on a form.
When you want to quickly find a header tag like <h1> to check the page title.
Syntax
Selenium Java
WebElement element = driver.findElement(By.tagName("tagName"));Replace tagName with the actual HTML tag you want to find, like "button" or "p".
This finds only the first matching element on the page.
Examples
Finds the first <button> element on the page.
Selenium Java
WebElement firstButton = driver.findElement(By.tagName("button"));Finds the first <p> (paragraph) element on the page.
Selenium Java
WebElement firstParagraph = driver.findElement(By.tagName("p"));Finds the first <img> element on the page.
Selenium Java
WebElement firstImage = driver.findElement(By.tagName("img"));Sample Program
This program opens a browser, goes to example.com, finds the first <h1> tag, prints its text, and checks if the text is not empty.
Selenium Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class FindElementByTagNameExample { public static void main(String[] args) { // Set path to chromedriver if needed // System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com"); // Find the first <h1> tag on the page WebElement header = driver.findElement(By.tagName("h1")); // Print the text inside the <h1> tag System.out.println("Header text: " + header.getText()); // Simple assertion to check header text is not empty if (!header.getText().isEmpty()) { System.out.println("Test Passed: Header found and has text."); } else { System.out.println("Test Failed: Header text is empty."); } } finally { driver.quit(); } } }
OutputSuccess
Important Notes
If no element with the given tag name exists, findElement throws NoSuchElementException.
Use findElements(By.tagName()) to get all elements with that tag name.
Tag names are case-insensitive in HTML, but use lowercase in Selenium for consistency.
Summary
findElement by tagName finds the first HTML element by its tag name.
It is useful for quick access to common tags like <button>, <input>, <h1>, etc.
Remember it returns only one element or throws an error if none found.