This jQuery function retrieves the hierarchical path of an element within a DOM tree. It traverses up the parent elements until it reaches the root.
The core functionality is encapsulated within the getPath
method, which is extended to the jQuery object prototype. The function recursively calls itself on the parent element until a specific condition is met.
/* jQuery function to get the hierarchical path of an element */ jQuery.fn.extend({ getPath: function(path) { if (typeof path === 'undefined') path = ''; // Initialize path if undefined let currentElementName = this.get(0).nodeName.toLowerCase(); let id = this.attr('id'); // Add ID to path if available, handling the special case of an element with id 'browser' if (typeof id !== 'undefined') { if (id === 'browser') { return path; // Stop recursion if id is 'browser' } else { path = `${currentElementName}#${id} ` + path; // Add id to path } } else { path = `${currentElementName} ` + path; // Add element name to path } // Recursive call to parent element return this.parent().length ? this.parent().getPath(path) : path.trim(); // Return trimmed path if parent doesn't exist } });
This improved version addresses potential issues:
currentElementName
instead of cur
)..length
before recursive call, preventing errors if the element is already at the root..trim()
.html.search
check which has been removed.This revised function provides a more reliable and efficient way to obtain the hierarchical path of any element within a jQuery context.
The above is the detailed content of jQuery Get Hierarchy Path of Element. For more information, please follow other related articles on the PHP Chinese website!