Score code, devs, and debt fast.

Start free trial

jQuery Get Hierarchy Path of Element

Sam Deering
Sam Deering
Published in
·Updated:

Share this article

SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools

7 Day Free Trial. Cancel Anytime.

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.

/*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);
        }
    }
});

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

determining an elements ancestorsjQuery

Share this article

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.