I have an XPath selector. How can I get the elements matching that selector using jQuery?
I've seen https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript but it doesn't use jQuery, and it seems a little too verbose, and I suppose it's not cross-browser.
Also, this http://jsfiddle.net/CJRmk/ doesn't seem to work.
If you are debugging or similar - In chrome developer tools, you can simply use
$x('/html/.//div[@id="text"]')
document.evaluate()
(DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.
First create an xpath selector function.
function _x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
To use the xpath selector with jquery, you can do like this:
$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');
Hope this can help.
Success story sharing
document.evaluate()
, which @WladimirPalant mentioned.document.evaluate()
. More info on the helper commands$x('/html/.//div[@id="text"]').hide();
must use instead this:$($x('/html/.//div[@id="text"]')).hide();
$x()
is NOT jQuery. It is returning HTML DOM..hide()
is a jQuery function, so you need to wrap the HTML DOM in a$()
to access jQuery functions, just like if you used any other native JS DOM functions.