I have this html block:
<td><a href="#" class=""> <i class="far fa-times mr-1"></i>Cancel</a></td>
I wrote the following xpath to find this Cancel anchor, but this is not working. What am I doing wrong?
//a[contains(text(), 'Cancel')]
The following xpath works but i need to learn what am i doing wrong in the above one:
//i[@class='far fa-times mr-1']/..
//a[contains(text(), 'Cancel')]
Issue: The reason above XPath expression is not working is because, above XPath looks for an anchor (<a>
) element containing the text Cancel
. However, the <a>
element in your HTML snippet doesn't directly contain the text Cancel
. Instead, it contains an <i>
element and then the text Cancel
.
Solution: Change the XPath expression as below:
//a[contains(., 'Cancel')]
XPath explanation: The .
represents the current node, so contains(., 'Cancel')
checks for the presence of "Cancel" text within the <a>
element and all of its descendants.