×
☰ See All Chapters

Selenium relative XPath using text() function

In the html code of an element, if attribute is duplicate or attribute itself is not present,  then use text() function to identify the element. In order to use text() function, the element should have text in the element’s html code.

Syntax:

//tagname[text()='text value of the tag']

OR

//tagname[.='text value of the tag']

Instead of text(), we can use dot (.) , the problem here with using dot (.) is sometimes, it returns the hidden element also present on the webpage, which might confuse the user. So the best practice is to use text() instead of using dot.

Few examples for relative xpath using text() for the below sample html code

<html>

</head>

<body>

<table align="center" width=90% cellspacing="2" cellpadding="2" >

        <tr>

                <td><button type="button">www.tools4testing.com</button></td>  

                <td><button type="button">www.java4coding.com</button></td>  

        </tr>

</table>

</body>

</html>

 

xpath=//button[text()='www.tools4testing.com']

Selects button with the text www.tools4testing.com

xpath=//button[text()='www.java4coding.com']

Selects button with the text www.java4coding.com

You can write the script and test these using our Test Page

selenium-relative-xpath-using-text-function-0
 
selenium-relative-xpath-using-text-function-1
 

All Chapters
Author