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?
The jQuery library supports a basic set of XPath selectors that we can use alongside CSS selectors, if we so desire. And with jQuery, both XPath and CSS selectors can be used regardless of the document type.
This document describes the interface for using XPath in JavaScript internally, in extensions, and from websites. Mozilla implements a fair amount of the DOM 3 XPath, which means that XPath expressions can be run against both HTML and XML documents.
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With