Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 10th, 2012  |  syntax: None  |  size: 1.34 KB  |  hits: 5  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to get the parent which contains the least of children?
  2. <ul class="containers">
  3.     <li>Matt</li>
  4.     <li>John</li>
  5.     <li>Mark</li>
  6. </ul>
  7. <ul class="containers">
  8.     <li>Roger</li>
  9.     <li>Bill</li>
  10.     <li>Lara</li>
  11.     <li>Miriam</li>
  12.     <li>Dylan</li>
  13.     <li>Harry</li>
  14. </ul>
  15.        
  16. var $el = $('ul.containers:first');
  17.  
  18. $('ul.containers').each(function(){
  19.   if( $(this).children().length < $(this).next('ul.containers').children().length ){
  20.     $el = $(this);
  21.   }
  22. });
  23.  
  24. console.log( $el ); //$el is now the parent with the least children.
  25.        
  26. var $el = $('ul.containers:first');
  27.  
  28. $('ul.containers').each(function(){
  29.   $el = $(this).children().length < $(this).next('ul.containers').children().length ? $(this) : $el ;
  30. });
  31.  
  32. console.log( $el ); //$el is now the parent with the least children.
  33.        
  34. var containers = $('.containers');
  35. var least_children = null;
  36. var smallest_container = null;
  37.  
  38. for(var i = 0; i < containers.length; i++)
  39. {
  40.     var container = containers[i];
  41.  
  42.     if(least_children === null)
  43.     {
  44.         least_children = container.childElementCount;
  45.         smallest_container = container;
  46.     }
  47.     else if(container.childElementCount < least_children)
  48.     {
  49.         least_children = container.childElementCount;
  50.         smallest_container = container;
  51.     }
  52. };
  53.  
  54. // smallest_container now contains the UL with the least children as a
  55. // HTMLElement