Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using xpath to select elements in jQuery?

Tags:

jquery

xpath

Is there a plugin to allow me to do this? It says here (XPath Compatibility Plugin) that the functionality was removed back in Jquery version 1.2 and the plugin it links is gone!

like image 355
significance Avatar asked Nov 26 '10 09:11

significance


People also ask

Can you select multiple elements in jQuery?

In jQuery, you can select multiple elements by separate it with a comma “,” symbol.

What is custom selector in jQuery?

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. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.


1 Answers

Most browsers support document.evaluate() for selecting elements with XPath expressions - no jQuery required. The only major browser lacking support is Internet Explorer. Dimitri Glazkov has created a library that will implement the missing functionality for IE, however.

var result = document.evaluate("//a[@href='#']", document, null, 0, null),
    item;

while (item = result.iterateNext()) {
    // item will be an <a> element with href="#" here
}

You could easily create a plugin to wrap this functionality too:

(function($) {
    $.xpath = function(exp, ctxt) {
        var item, coll = [],
            result = document.evaluate(exp, ctxt || document, null, 5, null);

        while (item = result.iterateNext())
            coll.push(item);

        return $(coll);
    }
})(jQuery);

// And call it like so:
$.xpath("//a[@href='#']").click(function () { return false; });
like image 88
Andy E Avatar answered Oct 23 '22 23:10

Andy E