Skip to content Skip to sidebar Skip to footer

How To Count The Number Of Elements On The First Row Of Their Parent Element

My question is, is there a way maybe in JavaScript that I can determine how many child elements are going to fit across the first row of a parent element? I would then multiply th

Solution 1:

Ok, I think I understand you better now. Try this code out. Run it as is and observe the count, then go to full-screen mode and run it again.

$(document).ready(function(){
   
    functioncountFirstRowItems(parentSelector, childSelector){
        var count = 0, theTop = undefined;
        $(parentSelector + " > " + childSelector).each(function(){
            var thisTop = $(this).offset().top;
            if(theTop === undefined){
                theTop = thisTop;
            }
            if(thisTop != theTop){
                returnfalse;
            }
            count++;
        });
        return count;
    }
    
    $('#btnCount').click(function(){
        $('#spnCount').html(
            countFirstRowItems('.outer', '.item')
        );
    });

    $('#spnCount').html(
        countFirstRowItems('.outer', '.item')
    );
    
});
.outer{
  padding:.5em;
  margin:.5em;
  box-shadow:inset 0px0px3px#aaa;
}
.item{
  margin:.5em;
  height:150px;
  width:100px;
  border:solid 1px#ddd;
  float:left;
  background-color:#fdfafa;
}
.clearfix{
  clear:both;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="btnCount">Count items on first row</button><spanid="spnCount">?</span><divclass='outer'><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='item'></div><divclass='clearfix'></div></div>

Post a Comment for "How To Count The Number Of Elements On The First Row Of Their Parent Element"