</>

Technology

Scenario-Based

Difficulty

Intermediate

Interview Question

How do you validate tooltip text on hover in Selenium?

Answer

Validating Tooltip Text on Hover

Tooltips appear on mouse hover. Selenium''s Actions class simulates real mouse movement to trigger them.

Method 1 — Read title Attribute (Native HTML Tooltip)

Native tooltips use the title attribute — no hover simulation needed:

Java
WebElement element = driver.findElement(By.id("helpIcon"));

// Read tooltip directly from attribute
String tooltipText = element.getAttribute("title");
System.out.println("Tooltip: " + tooltipText);
Assert.assertEquals(tooltipText, "Click here for help");

Method 2 — Hover + Read Tooltip Element (CSS/JS Tooltip)

Modern UI libraries show a separate DOM element on hover:

Java
WebElement hoverTarget = driver.findElement(By.cssSelector(".tooltip-trigger"));

// Hover over element
Actions actions = new Actions(driver);
actions.moveToElement(hoverTarget).perform();

// Wait for tooltip to appear
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement tooltip = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".tooltip-content"))
);

String tooltipText = tooltip.getText();
Assert.assertEquals(tooltipText, "This field is required");

Method 3 — JavaScript Tooltip (aria-label or data attribute)

Java
// Some tooltips use aria-label
String tooltip = element.getAttribute("aria-label");

// Some use data-tooltip attribute
String tooltip2 = element.getAttribute("data-tooltip");

Method 4 — Peek Into Shadow DOM / JS tooltip

Java
JavascriptExecutor js = (JavascriptExecutor) driver;
String tooltipText = (String) js.executeScript(
    "return arguments[0].getAttribute('data-original-title');", element
);

Tooltip Type Quick Guide

Tooltip TypeApproach
Native title attributeelement.getAttribute("title")
CSS tooltip (::before/::after)Hover + read content via JS
Bootstrap/Material tooltipHover + wait for .tooltip element
aria-labelgetAttribute("aria-label")
JS tooltipdata-original-title attribute

Follow AutomateQA

Related Topics