Search code examples
javaseleniumselenium-webdriverselenium-chromedriverwebdriverwait

how to get changed text in java selenium


<table>
    <tr>
        <td>hi</td>
    </tr>        
</table>
<button id="change" onclick="change()">change</button>
<script>
    function change(){
        $("table").empty();
        var $tr = $("<tr></tr>");
        $tr.append( $("<td>bye</td>") );
    }
</script>
WebDriver driver=new ChromeDriver(chromeOptions);
WebElement change= driver.findElement(By.id("change"));
change.click();

WebElement td=driver.findElement(By.xpath("//*table/tr/td[1]"));
System.out.println(td.getText());

I expected "bye", but it printed "hi".

How can I get dynamically changed text?


Solution

  • With the use of WebDriverWait explicit waits you can get the initial element text content. Then to wait for that text to no more be presented in that element after the click and then to get the new element text content. As following:

    WebDriverWait wait = new WebDriverWait(webDriver, 20);
    WebElement td =driver.findElement(By.xpath("//*table/tr/td[1]"));
    String oldText = td.getText();
    driver.findElement(By.id("change")).click();
    wait.until(ExpectedConditions.not(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//*table/tr/td[1]"), oldText)));
    System.out.println(td.getText());