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.
alert($("//a").length);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>_x000D_
<a href="a1.php"></a>_x000D_
<a href="a2.php"></a>
_x000D_
This question is related to
javascript
jquery
xpath
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.
If you are debugging or similar - In chrome developer tools, you can simply use
$x('/html/.//div[@id="text"]')
Source: Stackoverflow.com