Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the full path to an element?

Tags:

html

jquery

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

like image 604
Dylan Jones Avatar asked Mar 26 '11 13:03

Dylan Jones


3 Answers

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)

like image 115
Brad Christie Avatar answered Nov 02 '22 01:11

Brad Christie


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.

like image 40
Ja͢ck Avatar answered Nov 02 '22 01:11

Ja͢ck


.parents()

would that do it?

like image 2
clairesuzy Avatar answered Nov 02 '22 00:11

clairesuzy