
Untitled
By: a guest on
Aug 10th, 2012 | syntax:
None | size: 1.34 KB | hits: 5 | expires: Never
How to get the parent which contains the least of children?
<ul class="containers">
<li>Matt</li>
<li>John</li>
<li>Mark</li>
</ul>
<ul class="containers">
<li>Roger</li>
<li>Bill</li>
<li>Lara</li>
<li>Miriam</li>
<li>Dylan</li>
<li>Harry</li>
</ul>
var $el = $('ul.containers:first');
$('ul.containers').each(function(){
if( $(this).children().length < $(this).next('ul.containers').children().length ){
$el = $(this);
}
});
console.log( $el ); //$el is now the parent with the least children.
var $el = $('ul.containers:first');
$('ul.containers').each(function(){
$el = $(this).children().length < $(this).next('ul.containers').children().length ? $(this) : $el ;
});
console.log( $el ); //$el is now the parent with the least children.
var containers = $('.containers');
var least_children = null;
var smallest_container = null;
for(var i = 0; i < containers.length; i++)
{
var container = containers[i];
if(least_children === null)
{
least_children = container.childElementCount;
smallest_container = container;
}
else if(container.childElementCount < least_children)
{
least_children = container.childElementCount;
smallest_container = container;
}
};
// smallest_container now contains the UL with the least children as a
// HTMLElement