Search code examples
javascriptxpath

Evaluate XPath relative to context node


I am trying to evaluate an XPath relative to a particular DOM node. That is, I would like to access /html/body/div/a using the expression //a, while specifying that the XPath should be evaluated on the <div> element.

From the docs, it seems that the contextNode argument should work here.

<html>
  <body>
    <a href="#">outer</a>
    <div>
      <a href="#">inner</a>
    </div>
  </body>
</html>

I tried to evaluate the XPath on the <div> using the contextNode argument, but passing it had no effect. I would have expected that now the inner <a> element should be found.

Instead, document.evaluate('//a', div).iterateNext().innerText gives the text "outer".

https://jsfiddle.net/mt04y8db/


Solution

  • An absolute path starting with / searches from the document root node (of the context node) so either use .//a or descendant::a, perhaps sufficient for your sample, simply a.