2

As per my understanding of XPath, for any HTML or XML document:
$x("/node()") means $x("/child::node()") which means return the node which is a child of the context node. Here, the root node(/) is the context node. Therefore, it returns the html element.

$x("node()") means $x("child::node()") which also returns the same html element. But in this case, we have not provided the context node unlike in the above case. So, how does it identify the context node in this case ?

Also, are both the above XPath expressions syntactically and functionally same.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • 1
    I don't agree with the conclusion "Therefore, it returns the html element", the document node or root node can have comments and processing instructions (in XML, at least) before and/or after the root element which are also selected by `/node()`. And while XPath does not know DOCTYPE nodes I think in Chrome `$x('/node()')` will also include such a DOCTYPE node if present in the HTML document or probably XML document as well. – Martin Honnen Aug 18 '20 at 23:56

1 Answers1

1

The difference is that /node() specifies the context node absolutely as the document root (/), but node() relies upon an implied, relative context node.

How is an implied, relative context node determined? Well, based on context. ;-) For example, the hosting language will typically set the initial context node to the current node being matched or iterated. Then, within the evaluation of the XPath itself, each location step (separated via slashes, /) establishes the context node for the subsequent steps.

The $x(path, [startNode]) notation used in the Chrome console takes an optional second argument that can be used to specify the context node explicitly. By default, it is equal to the document root node, which leads to the observed behavior where $x("node()") and $x("/node()") returned the same results for a given document.

Also, are both the above XPath expressions syntactically and functionally same.

Clearly node() and child::node() are syntactically different, but, yes, they are semantically (or functionally, as you say) the same because the child:: axis is the default axis.

See also

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • 1
    Many thanks for such a clear and concise explanation along with the related posts. Every time I go through your answers, I get to learn a lot from your immense knowledge. – Sandesh Sawant Aug 19 '20 at 08:45