Javascript:在 jQuery 中使用 xpath

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12243661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:29:40  来源:igfitidea点击:

Javascript: use xpath in jQuery

javascriptjqueryxpath

提问by Adam Sh

I have, for example, the next XPath query:

例如,我有下一个 XPath 查询:

//div[span="something"]/parent::div/child::div[@class=\"someClass\"]

I want to use this XPath query in JavaScript:

我想在 JavaScript 中使用这个 XPath 查询:

return $("a:contains('Fruits')").mouseover();

I tried this:

我试过这个:

return $("div[span=\"something\"]/parent::div/child::div[@class=\"someClass\"]").mouseover();

But it didn't work. Is there another semantic for XPath queries in order to use them in JavaScript?

但它没有用。XPath 查询是否有另一种语义以便在 JavaScript 中使用它们?

采纳答案by georgebrock

You can re-write your xpath queries as CSS selectors:

您可以将 xpath 查询重写为 CSS 选择器:

$('div:has(> div > span:contains(something)) > div.someClass');

You can achieve the same effect as parent::using the :haspseduo selector to select an element based on its children: div.foo:has(> div.bar)will select all divelements with class foothat have a child divwith class bar. This is equivalent to div[@class="bar"]/parent::div[@class="foo"].

你可以达到同样的效果parent::使用:haspseduo选择器选择基于其子元素:div.foo:has(> div.bar)将选择所有div带班的元素foo有一个孩子div带班bar。这相当于div[@class="bar"]/parent::div[@class="foo"].

See:

看:

You could probably approach this in several other ways using various combinations jQuery's DOM traversal methods. For example, this would be a very direct translation of your xpath query:

您可能可以使用jQuery 的 DOM 遍历方法的各种组合以其他几种方式来解决这个问题。例如,这将是您的 xpath 查询的非常直接的翻译:

$('div:has(> span:contains(something))')  // //div[span="something"]
    .parent('div')                        // /parent::div
    .children('div.someClass');           // /child::div[@class="someClass"]

It's worth noting that div.someClassin CSS isn't the exact equivalent of div[@class="someClass"]in xpath. The CSS will match <div class='foo someClass bar'>, but the xpath won't. See Brian Suda's article on parsing microformats with XSLTfor more detail.

值得注意的是,div.someClass在 CSS 中并不完全等同于div[@class="someClass"]在 xpath 中。CSS 会匹配<div class='foo someClass bar'>,但 xpath 不会。有关更多详细信息,请参阅Brian Suda 关于使用 XSLT 解析微格式的文章

回答by Orwellophile

You could add the results of an existing XPath evaluation to a jQuery selection, I threw together this jquery extension that seems does it all for you.

您可以将现有 XPath 评估的结果添加到 jQuery 选择中,我将这个 jquery 扩展放在一起,它似乎为您完成了这一切。

Example usage:

用法示例:

$(document).xpathEvaluate('//body/div').remove()

Here's the add-in.

这是加载项。

$.fn.xpathEvaluate = function (xpathExpression) {
   // NOTE: vars not declared local for debug purposes
   $this = this.first(); // Don't make me deal with multiples before coffee

   // Evaluate xpath and retrieve matching nodes
   xpathResult = this[0].evaluate(xpathExpression, this[0], null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

   result = [];
   while (elem = xpathResult.iterateNext()) {
      result.push(elem);
   }

   $result = jQuery([]).pushStack( result );
   return $result;
}

回答by Dominator008

As the co-author of Wicked Good XPath, I certainly recommend it for cross browser XPath support (on HTML documents, you can try using it with XML documents but the support is incomplete).

作为Wicked Good XPath的合著者,我当然推荐它用于跨浏览器 XPath 支持(在 HTML 文档上,您可以尝试将它与 XML 文档一起使用,但支持不完整)。

We welcome any sort of correctness test / performance benchmark on our library. During development, the library has been tested on IE 7 through 10 plus the Android 2.2 browser which doesn't have native XPath support.

我们欢迎对我们的库进行任何类型的正确性测试/性能基准测试。在开发过程中,该库已在 IE 7 到 10 以及不具有本机 XPath 支持的 Android 2.2 浏览器上进行了测试。

回答by sv_in

There is no Cross-browser implementation as far as I know. There is a xpath pluginfor jQuery which says is still in developement.

据我所知,没有跨浏览器实现。jQuery有一个xpath 插件,它说仍在开发中。

Other than that there is a Google-authored pure JavaScript implementation of the DOM Level 3 XPath specification called wicked-good-xpathwhich is good.

除此之外,还有一个 Google 编写的 DOM Level 3 XPath 规范的纯 JavaScript 实现,称为wicked-good-xpath,这很好。

回答by spetsnaz

if you want to select an element inside an iframe, from parent window, you should change second parameter of evaulate() function to iframe's document element, like :

如果要从父窗口中选择 iframe 内的元素,则应将 evaulate() 函数的第二个参数更改为 iframe 的文档元素,例如:

var iFrameDocument = $('iframe#myPage').get(0).contentWindow.document;
xpathResult = this[0].evaluate(xpathExpression, iFrameDocument, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

回答by Constantinius

I'm not sure about the parent::divclause, but without it it should look like this:

我不确定该parent::div条款,但没有它它应该是这样的:

$('div[span="something"] div.someClass');

回答by Robin Winslow

jQuery only has limited support for XPath. You can see what it does support here: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors

jQuery 对 XPath 的支持有限。您可以在此处查看它支持的内容:http: //docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors

As mentioned by @Ameoo you can use the evaluate method, which is available in most modern browsers - except, predictably, IE: jquery select element by xpath

正如@Ameoo 所提到的,您可以使用在大多数现代浏览器中都可用的评估方法 - 除了可预见的 IE: jquery select element by xpath

回答by CosminO

read from here about the evaluatemethod : https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript

从这里阅读有关该evaluate方法的信息:https: //developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript

var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );