Jquery select element by xpath

I have an xpath selector. How can I get elements matching this selector using jquery?

I saw https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript , but it does not use jquery, and it seems a little too verbose, and I suppose its not a cross browser.

Also, this http://jsfiddle.net/CJRmk/ is not working ...

+49
javascript jquery xpath
Jun 23 '11 at 11:25
source share
3 answers

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only main browser is MSIE. However, jQuery supports the basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved to the plugin in the current version of jQuery, see https://plugins.jquery.com/xpath/ ) However, it simply converts XPath expressions to equivalent CSS selectors.

+16
Jun 23 '11 at 11:33
source share
— -

If you are debugging or similar. In Chrome Developer Tools, you can simply use

 $x('/html/.//div[@id="text"]') 
+110
Jun 13 '13 at 7:59
source share

First create an xpath select 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 the following:

 $(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text'); 

Hope this helps.

+18
Feb 03 '13 at 4:24
source share



All Articles