3

What is the difference between //div[contains(text(),'abc')] and //div[contains(.,'abc')]?

Is "." here is used as a regular expression meaning any text that starts with abc?

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
RISHI KHANNA
  • 354
  • 5
  • 23
  • 3
    Possible duplicate of [XPath: difference between dot and text()](http://stackoverflow.com/questions/38240763/xpath-difference-between-dot-and-text) – Guy Dec 08 '16 at 05:38

1 Answers1

4

The text() test selects all text node children of the context node.

The dot (.) selects the context node itself.

As arguments of contains() function, both . and text() are interpreted as string values which is concatenation of all the child text nodes (see "Element Nodes"):

The string-value of an element node is the concatenation of the string-values of all text node descendants of the element node in document order.

In the case of text(), the result is computed as concatenation of all direct text node values. In the case of ., the text values of all descendant text nodes are concatenated.

Consider this:

<html>
  <body>
    <div>abc</div>
    <div>444 <span>abc</span></div>
    <div>def</div>
    <div>123 abc</div>
  </body>
</html>

//div/text() selects the following:

  • "abc"
  • "444 "
  • "def"
  • "123 abc".

//div/.:

  • "abc"
  • "444 abc"
  • "def"
  • "123 abc"

Thus, //div[contains(text(),'abc')] selects only two divs:

<div>abc</div>
<div>123 abc</div>

while //div[contains(.,'abc')] selects all divs with a text node containing abc:

<div>abc</div>
<div>444 <span>abc</span></div>
<div>123 abc</div>
t72belt90
  • 25
  • 5
Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60