jquery select element by xpath

后端 未结 3 1512
萌比男神i
萌比男神i 2020-11-28 08:17

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_

相关标签:
3条回答
  • 2020-11-28 08:48

    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.

    0 讨论(0)
  • 2020-11-28 08:59

    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.

    0 讨论(0)
  • 2020-11-28 09:14

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

    $x('/html/.//div[@id="text"]')
    
    0 讨论(0)
提交回复
热议问题