FindThis

by TrueBlueAussie

HTML

<div class="level1" data-attr="Level 1">Level 1
    <div class="level2" data-attr="Level 2">Level 2
        <div class="level3" data-attr="Level 3">Level 3
            <div class="label">Label</div>
            <div class="starthere">HERE!</div>
        </div>
    </div>
    <div class="level2" data-attr="Level 2">Level 2
        <div class="level3" data-attr="Level 3">Level 3
            <div class="label">Label</div>
            <div class="starthere">Also HERE!</div>
        </div>
    </div>
    <div class="level2" data-attr="Level 2">Level 2
        <div class="level3" data-attr="Level 3">Level 3
            <div class="label">Label</div>
        </div>
    </div>
</div>

JavaScript

// Add findThis method to jQuery (with a custom :this check)
jQuery.fn.findThis = function (selector) {
    // If we have a :this selector
    if (selector.indexOf(':this') > 0) {
        var ret = $();
        for (var i = 0; i < this.length; i++) {
            var el = this[i];
            var id = el.id;
            // If not id already, put in a temp (unique) id
            el.id = 'id'+ new Date().getTime();
            var selector2 = selector.replace(':this', '#' + el.id);
            ret = ret.add(jQuery(selector2, document));
            // restore any original id
            el.id = id;
        }
        ret.selector = selector;
        return ret;
    }
    // do a normal find instead
    return this.find(selector);
}

// Test case
$(function () {
    $('.starthere').findThis('.level3:has(:this) .label').css({
        color: 'red'
    });
});