amitabhaghosh197
10/18/2015 - 5:04 PM

jQuery plugin: .deepest()

jQuery plugin: .deepest()

(function ($) {
    $.fn.deepest = function (selector) {
        var deepestLevel  = 0,
            $deepestChild,
            $deepestChildSet;
     
        this.each(function () {
            $parent = $(this);
            $parent
                .find((selector || '*'))
                .each(function () {
                    if (!this.firstChild || this.firstChild.nodeType !== 1) {
                        var levelsToParent = $(this).parentsUntil($parent).length;
                        if (levelsToParent > deepestLevel) {
                            deepestLevel = levelsToParent;
                            $deepestChild = $(this);
                        } else if (levelsToParent === deepestLevel) {
                            $deepestChild = !$deepestChild ? $(this) : $deepestChild.add(this);
                        }
                    }
                });
            $deepestChildSet = !$deepestChildSet ? $deepestChild : $deepestChildSet.add($deepestChild);
        });
            
        return this.pushStack($deepestChildSet || [], 'deepest', selector || '');
    };
}(jQuery));
$('#nestedExample')
    .deepest()
        .css('background-color', 'LightGray')
    .end()
    .deepest('p')
        .css('background-color', 'Yellow')
    .end()
    .deepest('.strong')
        .css('text-transform', 'uppercase');
$('.set')
    .deepest()
        .css('border-width', '3px')
    .end()
    .css('border-color', 'Red');
div, p {
    margin: 2px;
    padding: 2px;
    min-height: 1em;
    text-align: center;
}
div {
    border: 1px solid Blue;
} 
p {
    border: 1px dotted Gray;
}
.strong {
    font-weight: bold;
}
<div id="nestedExample">
    <div class="set">
        <div>
            <div></div>
        </div>
    </div>
    <div class="set empty"></div>
    <div class="set">
        <div>
            <div>
                <p class="strong">One</p>
            </div>
        </div>
    </div>
    <div class="set">
        <div>
            <div>
                <p class="strong">Two</p>
            </div>
        </div>
    </div>
    <div class="set">
        <div>
            <p class="strong">Buckle my shoe</p>
        </div>
    </div>
    <div class="set">
        <div>
            <div>
                <div>
                    <div id="deepest"></div>
                </div>
            </div>
        </div>
    </div>
</div>

jQuery plugin: .deepest()

Get the deepest descendants matching an optional selector of each element in the set of matched elements.

A Pen by Gerald on CodePen.

License.

Installation

Download jQuery-deepest.js below and include it either as an external file, or concatenate it with other scripts to reduce HTTP requests, or simply copy & paste the raw code into an embedded script on your page.

Example Usage

See my blog post or the associated example files below.