jQuery Get Hierarchy Path of Element

By Sam Deering

jQuery function to get hierarchy path of element by determining an elements ancestors and looping through it’s parent elements until the root of the tree has been reached.

Online Demo

/*jQuery function to create path function used to get the path of the node in the tree*/
    getPath: function (path) { /*The first time this function is called, path won't be defined*/
        if (typeof path == 'undefined') path = ''; /*Add the element name*/
        var cur = this.get(0).nodeName.toLowerCase();
        var id = this.attr('id'); /*Add the #id if there is one*/
        if (typeof id != 'undefined') { /*escape goat*/
            if (id == 'browser') {
                return path;
        var html = this.html();
        if ('
  • ' + path);         } else {             return this.parent().getPath(path);         }     } });
    • manohar

      is live demo working? because when i upload a J query file it is throwing error.



    Because We Like You
    Free Ebooks!

    Grab SitePoint's top 10 web dev and design ebooks, completely free!

    Get the latest in JavaScript, once a week, for free.