Returning the full path to an element?

后端 未结 4 1733
梦毁少年i
梦毁少年i 2020-12-31 20:31

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
相关标签:
4条回答
  • 2020-12-31 21:07

    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)

    0 讨论(0)
  • 2020-12-31 21:07

    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.

    0 讨论(0)
  • 2020-12-31 21:20

    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

    0 讨论(0)
  • 2020-12-31 21:27

    .parents()

    would that do it?

    0 讨论(0)
提交回复
热议问题