JSFiddle - React, Tailwind, and code Playground

by Farzad Cyrus

HTML

<div class="parent">
    <div class="interference">
        <div class="goal">
            This whole thing should be highlighted
            <div class="parent">
                <div class="interference">
                    <div class="goal">Not this</div>
                </div>
            </div>
        </div>
    </div>
</div>
<hr />
<div class="parent">
    <div class="interference">
        <div class="goal test">
            Calling it on this
            <div class="parent">
                <div class="interference">
                    <div class="goal">but only this should be highlighted</div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.goal {
    background: #fff;
}

JavaScript

(function($) {
    $.fn.closest_descendent = function(filter) {
        var $found = $(),
            $currentSet = this; // Current place
        while ($currentSet.length) {
            $found = $currentSet.filter(filter);
            if ($found.length) break;  // At least one match: break loop
            // Get all children of the current set
            $currentSet = $currentSet.children();
        }
        return $found.first(); // Return first match of the collection
    }    
})(jQuery);


$(document).ready(function() {
    console.log($('.parent').closest_descendent('.goal').css('background', '#ccc'));
    console.log($('.test').closest_descendent('.goal').css('background', '#eee'));
});