user2251831
user2251831

Reputation: 41

Xpath/ search input node by text

I have a search box (<input> element), and I try to get the element by the text that written into it.

I try to do the next:

// input [@value= "my text"] 

but it doesn't work (just to be clear - the value is not attribute of the input element. accully, when I do inspect element, I don't see the text that written in this text box).

<div class="EwdOOOOO">
 <div class="GOOOEOOO">Hello </div> 
 <input type="text" class="GOBLEOOO"> 
</div>

and the seatch box I put:

"How are you?"

You can see that "How are you?" isn't found in the DOM.

Thanks.

Upvotes: 2

Views: 30146

Answers (2)

nilesh
nilesh

Reputation: 14289

See my answer here. Sometimes the text value that you are setting is assigned as a "value" attribute of text box and not as "text"

WebElement input = driver.findElement(By.cssSelector("input[type='text']"));
input.sendKeys(enteredValue)
String retrievedText = input.getAttribute("value");
if(retrievedText.equals(enteredValue)){
 //do stuff
}

Upvotes: 0

e1che
e1che

Reputation: 1251

Are you sure to get your input and populate it ?

like :

WebElement input = driver.findElement(By.xpath("//input[@class='GOBLEOOO']"));
input.sendKeys("How are you?");

So you can get your element like that :

WebElement inputByValue = driver.findElement(By.xpath("//input[@value='my text']"));

or you have another way to do that

WebElement inputByValue= driver.findElement(By.xpath("//input[contains(@value,'my text')]"));

contains() return true if the value of your attribute @value contains the next parameter (string)

Because there is always a value attribute in an input since you type values in. Here for more Input specs.


If you want to found an element with the value you typed in the input field you can use this xpath.

// you get the value you typed in the input
String myValue = driver.findElement(By.xpath("//input[@class='GOBLEOOO']")).getAttribute("value"); 

//you get a element that contains myValue into his attributes
WebElement element = driver.findElement(By.xpath("//*[contains(@id ,myValue) or contains(@value, myValue) or contains(@name, myValue)]"));

Upvotes: 5

Related Questions