Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
<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>
like image 498
Quamis Avatar asked Jun 23 '11 11:06

Quamis


People also ask

Can we use XPath in jQuery?

XML Path Language (XPath) is a type of language for identifying different elements or their values within XML documents, similar to the way CSS identifies elements in HTML documents. The jQuery library supports a basic set of XPath selectors that we can use alongside CSS selectors, if we so desire.

What is a jQuery selector?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more.

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).


3 Answers

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

$x('/html/.//div[@id="text"]')
like image 174
Jeppe Liisberg Avatar answered Nov 14 '22 22:11

Jeppe Liisberg


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.

like image 42
Wladimir Palant Avatar answered Nov 14 '22 22:11

Wladimir Palant


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.

like image 26
Nanang El Sutra Avatar answered Nov 14 '22 20:11

Nanang El Sutra