I am looking for a way to find the full path to an element on click.
For example, lets say I have this HTML code:
- i
If you want the plugin approach:
(function($){
$.fn.extend({
getFullPath: function(stopAtBody){
stopAtBody = stopAtBody || false;
function traverseUp(el){
var result = el.tagName + ':eq(' + $(el).index() + ')',
pare = $(el).parent()[0];
if (pare.tagName !== undefined && (!stopAtBody || pare.tagName !== 'BODY')){
result = [traverseUp(pare), result].join(' ');
}
return result;
};
return this.length > 0 ? traverseUp(this[0]) : '';
}
});
})(jQuery);
Specify a selector or object to jQuery and it will get the full path of it. stopAtBody
is optional, but if supplied as true it will only traverse up to the <BODY>
tag (making it a valid jQuery selector).
DEMO (Click the LI to see their path revealed)
This is how you can reconstruct the full path:
var q = $(this)
.parentsUntil('body')
.andSelf()
.map(function() {
return this.nodeName + ':eq(' + $(this).index() + ')';
}).get().join('>');
Inspired by this answer.
Did you read about the parents() function ? http://api.jquery.com/parents/
You can get something like this
My parents are: SPAN, P, DIV, BODY, HTML
.parents()
would that do it?