How can I get the current contents of an element in webdriver?

We can get the current contents of an element in Selenium webdriver. For the elements having tagname as <input> we have to use the getAttribute() method and pass the value parameter as an argument to that method to obtain the current contents.

For the elements without an input tag we have to use the getText() method to obtain the current contents. First of all we have to identify the element with the help of the locators.

Let us try to get the content Selenium inside the edit box and its above text content – You are browsing the best resource for Online Education.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;

public class ElementContent{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify elements
      WebElement t = driver.findElement(By.cssSelector("h4"));
      WebElement l = driver.findElement("gsc-i-id1"));
      // getAttribute() with value for content in edit box
      System.out.println("Content in edit box: " + l.getAttribute("value"));
      //getText() to get content
      System.out.println("Content in element: " + t.getText());