The code you have provided looks correct, but it might not be working as expected because the element you are trying to click might not be visible or enabled when you try to execute the JavascriptExecutor
code to retrieve the inner text.
Here's an alternate approach that you can try to get the content of a clickable element in Selenium:
1 Click the element using click()
method:
webElement2.click();
2 Retrieve the inner text of the element using getText()
method:
String tagContent = webElement2.getText();
By clicking the element first, you ensure that it is visible and enabled before trying to retrieve the inner text.
If you still face issues with this approach, you can try to add a small wait before retrieving the inner text to allow the element to fully load and render on the page. You can use the WebDriverWait
class for this purpose, like below:
WebElement webElement2 = driver.findElement(By.xpath("//yourXpath"));
webElement2.click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//yourXpath")));
String tagContent = webElement2.getText();
The visibilityOfElementLocated
method waits for the element to become visible on the page before continuing.
I hope this helps you to get the content of a clickable element in Selenium.