Skip to content

Instantly share code, notes, and snippets.

@geraldfullam
Last active September 24, 2019 14:21
Show Gist options
  • Save geraldfullam/3a151078b55599277da4 to your computer and use it in GitHub Desktop.
Save geraldfullam/3a151078b55599277da4 to your computer and use it in GitHub Desktop.
jQuery plugin: .deepest()

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.

<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>
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;
}
$('#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');
(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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment