using xpath to select elements in jQuery?

13,368

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; });
Share:
13,368
significance
Author by

significance

Updated on July 25, 2022

Comments

  • significance
    significance almost 2 years

    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!

  • Michael
    Michael about 11 years
    a better solution is shown here stackoverflow.com/questions/2068272/… where you can just use the string as a native css selector
  • Andy E
    Andy E about 11 years
    @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.