jQuery Deepest function
Returns the deepest nested child element
HTML
<div class="top">
<div class="div_chain_1">
<div class="div_chain_2">
<div class="div_chain_3">
I'm deep in divs
</div>
</div>
</div>
<div class="mixed_1">
<ul class="mixed_2">
<li class="mixed_3"><img class="mixed_6">I'm a deep image</img></li>
<li class="mixed_4"><span class="mixed_7">I'm a deep span</span></li>
<li class="mixed_5"><div class="mixed_7">I'm the deepest div ever</div></li>
</ul>
</div>
</div>
JavaScript
/**
* Deepest
* find the most deeply nested child(ren) of an element
* @returns jquery obj
**/
(function( $ ) {
$.fn.deepest = function(selector){
var targ = $(this);
var result = [];
//If there is no selector just drill down to the furthest child
if (typeof (selector) === 'undefined') {
selector = "*";
while ( $(targ).children(selector).length ) {
targ = $(targ).children(selector);
}
return targ;
};
//Get to the deepest point from which the selector can be seen
while ( $(targ).find(selector).length ) {
targ = $(targ).children('*');
}
//Only keep the elements that match the selector
targ = $(targ).each(function(i, obj){
if ($(obj).is(selector) ) {
result.push(obj)
}
});
return $(result);
};
})( jQuery );
//to test the function
$(function(){
$(".top").deepest('li').css({'background-color':'yellow'})
console.log($(".top").deepest("div"))
})