We can replace inner html of any element existing on the page.

To do this we should use JavascriptExecutor and execute a script.

In general Java code looks just like this

String script = "arguments[0].innerHTML='" + StringEscapeUtils.escapeEcmaScript(innerHtml) + "'";
((JavascriptExecutor) driver).executeScript(script, webElement);

Selenium WebDriver. Replace inner html

Modify text of element

Let’s try to implement this 2 steps scenario with Selenium WebDriver

1. Get to www.google.com


Link text to be replaced using Selenium WebDriver

WebElement webElement = driver.findElement(By.linkText("Gmail"));
String script = "arguments[0].innerHTML='Hotmail'";
((JavascriptExecutor) driver).executeScript(script, webElement);

Link text replaced using Selenium WebDriver

What links/pages on the Internet would you modify? :)

Replace page’s content

Using the same approach we can replace the content of the page with html from a file. Let’s implement that.

The file should be saved in the resources folder.

String htmlFromFile = readFileIntoString(fileName);
WebElement e = getDriver().findElement(By.tagName("html"));
String script = "arguments[0].innerHTML='" 
                + StringEscapeUtils.escapeEcmaScript(htmlFromFile) + "'";
((JavascriptExecutor) getDriver()).executeScript(script, e);

Note: See How to read file to String

You may also find these posts interesting: