$.fullSelector() = Recursively Generate the Selector of an Element

Made by Adam Schwartz

by adamschwartz

HTML

<div id="awesome_id">
    <a class="class1 class2"><span id="the_span" class="yomama"></span></a>
</div>

JavaScript

(function($){
    $.fn['elementSelector'] = function() {
        var el = this,
            s = el.get(0).tagName;
        if (el.attr('id') && el.attr('id') !== '') {
            s += '#' + el.attr('id');
        }
        if (el.attr('class') && el.attr('class') !== '') {
            s += '.' + el.attr('class').replace(/\s+/g, '.');
        }
        return s.toLowerCase();
    };

    $.fn['fullSelector'] = function(steps) {
        var el = this, i = 0, s = '', steps = steps || 100;
        while (el.get(0).tagName) {
            i++;
            if (i > steps) { break; }
            s = el.elementSelector() + (i > 1 ? ' > ' : '') + s;
            el = el.parent();
        }
        return s;
    };
})(jQuery);

$(function(){
    $('body').append($('span').fullSelector(3));
});