Skip to content Skip to sidebar Skip to footer

JQuery - How Do I Count Children And Apply Percentage Based Width

How can I use jQuery to count the number of child elements (in this case list elements) inside div id #foo and then divide 100 / (# of counted child elements). The last step would

Solution 1:

$('someelement').width((100 / $('#foo').find('li').length));

You should do a check if the .length is zero, to avoid a division by zero.


Solution 2:

Try this(it takes care of case when there are not children in foo):

var el = $('#foo');
var len = el.children().length;
if(len > 0){
    len = 100/len;
    el.css("width",  len + "px"); 
} 

Solution 3:

var count = $('#foo > *').length;
$('#bar').css({width:(100/count)+'%'});

Solution 4:

<html>
<head>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js" 
type="text/javascript"></script>
</head>
<body>
    <div id="foo">
        <ul>
            <li>Baseball</li>
            <li>Basketball</li>
            <li>Football</li>
            <li>Soccer</li>
            <li>Hockey</li>
        </ul>
    </div>
    <script type="text/javascript">
        $(function () {
            var sWidth = "auto";
            var liLength = $("#foo li").length;
            alert(liLength);
            if (liLength > 0) {
                sWidth = (100 / liLength) + "%";
            }
            $("#foo").width(sWidth);
            alert(sWidth);
        });
    </script>
</body>
</html>

Post a Comment for "JQuery - How Do I Count Children And Apply Percentage Based Width"