If double slash (//) is used 2 times in XPath, what does it mean?

What does a double-slash used twice in an XPath selector mean?

Suppose I'm using a path like:

//div[@id='add']//span[@id=addone']

Solution 1:

A double slash "//" means any descendant node of the current node in the HTML tree which matches the locator.

A single slash "/" means a node which is a direct child of the current.

//div[@id='add']//span[@id=addone'] will match:

<div id="add">
  <div>
    <span id="addone">
  </div>
</div>

And:

<div id="add">
    <span id="addone">
</div>

//div[@id='add']/span[@id=addone'] will match only the second HTML tree.

Solution 2:

Double slash (//) is the descendant-or-self axis; it is short for /descendant-or-self::node()/.

In your example XPath:

//div[@id='add']//span[@id='addone']
  • The first time // appears, it selects all div elements in the document with an id attribute value equal to 'add'.
  • The second time // appears, it selects all span elements that are descendents of each of the div elements selected previously.
  • Note that using two double slashes twice is different than just using double slash once. For example, //span[@id='addone'] would select all span elements with @id='addone' in the entire document, regardless of whether they are a descendent of a div with @id='add'.

Solution 3:

If you'd have this:

<div id='add'>
   <ul>
      <li>
        <span id='add one' />
      </li>
   </ul>
</div>

Then

//div[@id='add']//span[@id='addone']

will result in the span because the second // means you look for any child relative to

div[@id='add']

that is span[@id='add one'].

If you'd use one slash

//div[@id='add']/span[@id='addone']

then of course you won't find it because then you look for a direct child and you'd have to use

//div[@id='add']/ul/li/span[@id='addone']

So the second // is very useful in avoiding extra hierarchy in your XPaths.