I have, for example, the next XPath query:
//div[span="something"]/parent::div/child::div[@class=\"someClass\"]
I want to use this XPath query in JavaScript:
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?
You can re-write your xpath queries as CSS selectors:
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 alldivelements with classfoothat have a childdivwith classbar. This is equivalent todiv[@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:
It’s worth noting that
div.someClassin CSS isn’t the exact equivalent ofdiv[@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.