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:
<div> <ul> <li>item 1</li> <li>item 2</li> </ul> </div>
<div> <ul> <li>item 1</li> <li>item 2</li> </ul> </div>
I want to be able return the path (don't know what else to call it) to the clicked element. alert() will do for now.
Lets say I clicked on the second li element in the second div. I would like a call back of:
div:eq(1) li:eq(1)
If I clicked on the first li element of the first div, it would be:
div:eq(0) li:eq(0)
How would I do this?
Is there a plugin out that can do this, or would I need to make it from scratch to get the index of element in the path?
Thanks :)
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.
.parents()
would that do it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With