We often get confused when fetching text or value entered from a textBox on HTML DOM.
in this post we will see how we can get the text entered from textBox and then we will understand getText() vs getAttribute(“value”).
How to fetch text from textBox
For this we will consider the Full Name textbox from signup portal
Here is the HTML DOM for the textbox
To get the text entered from textbox, we will be using getAttribute(“value”) method not the getText().
WebElement el = driver.findElement(By.id("username")) el.sendKeys("QAVBOX") String str = el.getAttirbute("value") //this will return string as "QAVBOX"
In the above code, if you use String str = el.getText() //it will return null
getAttirbute(“value”) is used also to fetch the value attribute of an element, like below
Let’s say we want to get the value of this Home button
WebElement el = driver.findElement(By.name("home")) String str = el.getAttirbute("value") //this will return the value as "Home"
Use of getText()
Where as the getText() method will return the text present on the element or the string present in an enclosed opening and closing tag of an element.
Let’s look into this below example – the Full Name label element.
WebElement el = driver.findElement(By.id("lblname")) String str = el.getText() //this will return the value as "Full Name"
In above code, getText() will return the the string present on the enclosed label element.