JQuery – get element selector / path

Old piece of code I had to hunt out today, builds selector to the passed in element

/* Get the jquery selector for the specified element */
jQuery.fn.getPath = function (removeClasses) {
    if (this.length != 1) throw 'Requires one element.';
    var css = null;
    if (removeClasses) {
        css = $(this).prop('class');
        //remove local classes and get path
        $(this).removeClass(removeClasses);
    }
    var path, node = this;
    while (node.length) {
        var realNode = node[0];
        var name = (
            realNode.localName ||
            realNode.tagName ||
            realNode.nodeName
        );
        if (!name || name == '#document') break;
        name = name.toLowerCase();
        if (realNode.id) {
            return name + '#' + realNode.id + (path ? '>' + path : '');
        } else if (realNode.className) {
            name += '.' + realNode.className.split(/\s+/).join('.');
        }
        var parent = node.parent(), siblings = parent.children(name);
        if (siblings.length > 1) name += ':eq(' + siblings.index(node) + ')';
        path = name + (path ? '>' + path : '');
        node = parent;
    }
    if (removeClasses) {
        elem.prop('class', css);
    }
    return path;
};

Leave a Reply

Your email address will not be published. Required fields are marked *