英文:
Evaluate XPath relative to context node
问题
我正在尝试相对于特定DOM节点评估XPath。也就是说,我想使用表达式 //a 访问 /html/body/div/a,同时指定XPath应该在 <div> 元素上进行评估。
从文档来看,似乎 contextNode 参数应该在这里起作用。
<html>
<body>
<a href="#">outer</a>
<div>
<a href="#">inner</a>
</div>
</body>
</html>
我尝试使用 contextNode 参数在 <div> 上评估XPath,但传递它没有效果。我本来希望现在可以找到内部的 <a> 元素。
相反,document.evaluate('//a', div).iterateNext().innerText 返回文本 "outer"。
https://jsfiddle.net/mt04y8db/
英文:
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".
答案1
得分: 0
绝对路径以 / 开头,从上下文节点的文档根节点开始搜索,因此可以使用 .//a 或 descendant::a,对于您的示例可能足够简单,只需使用 a。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论