skip to Main Content

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']/..

2

Answers


  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.

    Login or Signup to reply.
  2. The problem is that the first argument of contains should be a single string. And since a has 2 text-nodes, it fails. The first text-node is the white-space only node, the second is the one with Cancel inside.

    I see two alternatives:

    1. //a[contains(., 'Cancel')]
      The . will combine all descendent text-nodes into one string.

    2. //a[contains(text()[normalize-space()], 'Cancel')] . The [normalize-space()]-predicate will select only those text-nodes that have besides white-space actual character-data. Ans since that is only one, it will succeed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search