10

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!

hakre
  • 193,403
  • 52
  • 435
  • 836
significance
  • 4,797
  • 8
  • 38
  • 57

1 Answers1

12

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; });
ug_
  • 11,267
  • 2
  • 35
  • 52
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • a better solution is shown here http://stackoverflow.com/questions/2068272/getting-a-jquery-selector-for-an-element where you can just use the string as a native css selector – Michael Jun 02 '13 at 19:40
  • 1
    @Michael: that question and solution are unrelated to this one. This one asks how you can select elements using XPath syntax, that one asks how you can create a CSS selector for an already selected element. You can't really say either is better than the other because they both approach different problems. – Andy E Jun 03 '13 at 09:34