If double slash (//) is used 2 times in XPath, what does it mean?
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.
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 alldiv
elements in thedocument with anid
attribute value equal to'add'
. - The second time
//
appears, it selects allspan
elements that aredescendents of each of thediv
elements selected previously. - Note that using two double slashes twice is different than just usingdouble slash once. For example,
//span[@id='addone']
would selectallspan
elements with@id='addone'
in the entire document, regardless of whether they are a descendent of adiv
with@id='add'
.
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.