jQuery select element by XPath

JavascriptJqueryXpath

Javascript Problem Overview


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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<a href="a1.php"></a>
<a href="a2.php"></a>

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQuamisView Question on Stackoverflow
Solution 1 - JavascriptJeppe LiisbergView Answer on Stackoverflow
Solution 2 - JavascriptWladimir PalantView Answer on Stackoverflow
Solution 3 - JavascriptNanang El SutraView Answer on Stackoverflow