ChatGPT解决这个技术问题 Extra ChatGPT

jQuery select element by XPath

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);


J
Jeppe Liisberg

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

@GregT ... and Firefox
@AloisMahdal, it looks like it's a Firebug thing (not 100% sure that it isn't also part of Firefox). Documentation on Firebug's site. It's also just shorthand for document.evaluate(), which @WladimirPalant mentioned.
Firefox developer tools implement it as well. And sure enough, it's a very simple convenience wrapper around document.evaluate(). More info on the helper commands
And for select and use functions on it, this does not work: $x('/html/.//div[@id="text"]').hide(); must use instead this: $($x('/html/.//div[@id="text"]')).hide();
Note that $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.
W
Wladimir Palant

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.


It's an old version of jQuery API for selectors
@Karolis: You are right, looks like this functionality has been moved into a plugin. I edited my answer to add this information.
N
Nanang El Sutra

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.


I think this wont works if document uses namespace and in IE10-11 (XPath not supported).
Thanks, I have used your _x() function in Behat/Mink code to fix find('xpath', 'xpath expression')'s unsufficient results in some situations.