JavaScript
Article
By Sam Deering

jQuery Get Hierarchy Path of Element

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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

--ADVERTISEMENT--

/*jQuery function to create path function used to get the path of the node in the tree*/
jQuery.fn.extend({
    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 (html.search('
  • ' + path);         } else {             return this.parent().getPath(path);         }     } });
  • Login or Create Account to Comment
    Login Create Account
    Recommended
    Sponsors
    Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?