jQuery function to generate selection path from container

jQuery function to generate selection path from container


It would be nice to have a function in the code to generate a 'query'
selector path to any element from any containing element. Sort of like
a jQuery equivalent of an xpath.
I just put together the following as an example of what it might look
like (can probably be made more efficient .. and I'm not sure if using
eq() provides the fastest selector path when resolved):
$.fn.extend({
        /**
         * Return a valid jQuery selector path to an object from a container
         * root - specify a root element from which to generate the path
         *
         * If no root is specified, then path is given from the document
root
         * If root is same as element, no path is returned (undefined)
         * If root is not actually a parent of this element, then no path is
returned (undefined);
         *
         */
        path : function(root) {
                    var r;
                    if(root) {
                        r = $(root)[0];
                    } else {
                        r = $()[0];
                    }
                    var el = this[0];
                    if(el) {
                        var path = "";
                        while(el && el.parentNode && el != r) {
                            if(el.nodeType == 9) { return; } //reached document node, no
root provided (probably, b/c given root is not a valid parent of this
node)
                            path = " > " + el.tagName.toLowerCase() + ":eq(" + $(el).prevAll
(el.tagName).size() + ") " + path;
                            var el = el.parentNode;
                        }
                    }
                    return path;
                }
    });