Get a selector path from a jquery object

Get a selector path from a jquery object


Earlier this year this posted:
http://groups.google.com/group/jquery-dev/browse_thread/thread/aa060b1945527d60
I found it helpful and made a few modifications. Namely if one of the
parent nodes has an id it uses said parent as the root.
$.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) {
// reached document node, no root provided.
return;
}
if (el.id){
path = el.tagName.toLowerCase()+"#"+el.id+"
"+path;
break;
} else {
path = el.tagName.toLowerCase()+":eq("+
$(el).prevAll(el.tagName).size()+") "+path;
}
var el = el.parentNode;
}
}
return path;
}
});