Dylan Jones
Dylan Jones

Reputation: 301

Returning the full path to an element?

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 :)

Upvotes: 8

Views: 8174

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173572

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.

Upvotes: 6

Brad Christie
Brad Christie

Reputation: 101614

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)

Upvotes: 6

clairesuzy
clairesuzy

Reputation: 27624

.parents()

would that do it?

Upvotes: 2

johnlemon
johnlemon

Reputation: 21459

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

Upvotes: 0

Related Questions