Javascript:在jQuery中使用xpath [英] Javascript: use xpath in jQuery
问题描述
例如,我有下一个XPath查询:
I have, for example, the next XPath query:
//div[span="something"]/parent::div/child::div[@class=\"someClass\"]
I想在JavaScript中使用此XPath查询:
I want to use this XPath query in JavaScript:
return $("a:contains('Fruits')").mouseover();
我试过这个:
return $("div[span=\"something\"]/parent::div/child::div[@class=\"someClass\"]").mouseover();
但它不起作用。 XPath查询是否有另一种语义才能在JavaScript中使用它们?
But it didn't work. Is there another semantic for XPath queries in order to use them in JavaScript?
推荐答案
您可以将您的xpath查询重写为CSS选择器:
You can re-write your xpath queries as CSS selectors:
$('div:has(> div > span:contains(something)) > div.someClass');
您可以达到与 parent :: $ c $相同的效果c>使用
:有
pseduo选择器根据子元素选择一个元素: div.foo:has(> div.bar)
将选择所有 div
元素,其类 foo
有一个孩子 div
,类 bar
。这相当于 div [@ class =bar] / parent :: div [@ class =foo]
。
You can achieve the same effect as parent::
using the :has
pseduo selector to select an element based on its children: div.foo:has(> div.bar)
will select all div
elements with class foo
that have a child div
with class bar
. This is equivalent to div[@class="bar"]/parent::div[@class="foo"]
.
参见:
- jQuery API: Selectors
- Sizzle documentation
您可以使用各种组合以其他几种方式处理此问题 jQuery的DOM遍历方法。例如,这将是您的xpath查询的非常直接的翻译:
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:
$('div:has(> span:contains(something))') // //div[span="something"]
.parent('div') // /parent::div
.children('div.someClass'); // /child::div[@class="someClass"]
值得注意的是<$ CSS中的c $ c> div.someClass 与xpath中的 div [@ class =someClass]
不完全相同。 CSS将匹配< div class ='foo someClass bar'>
,但xpath不会。请参阅 Brian Suda关于使用XSLT解析微格式的文章更多细节。
It's worth noting that div.someClass
in 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 XSLT for more detail.
这篇关于Javascript:在jQuery中使用xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!