Xpath/ search input node by text

28,917

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)]"));
Share:
28,917
user2251831
Author by

user2251831

Updated on July 09, 2022

Comments

  • user2251831
    user2251831 almost 2 years

    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.