Gareth Gillman
Gareth Gillman

Reputation: 353

jQuery count number of li's in each ul

I am trying to add a width to LI elements based on how many li's there are e.g.

I have got part way there with the following:

$(document).ready(function(){
 var count = $('#main-menu li ul > li').size();
 var width = 100/count;
 $('header nav#main-menu li ul li').css("width",width+"%");
});

The problem it's counting all the elements in total (including children). Is this possible?

Upvotes: 0

Views: 3979

Answers (2)

Chris Dixon
Chris Dixon

Reputation: 9167

$(document).ready(function(){
   $.each($('#main-menu li ul'), function() {
       var children = $(this).find(">li");
       var count = children.length;
       var width = 100/count;
       children.css("width", width + "%");
   });
});

Upvotes: 1

Alnitak
Alnitak

Reputation: 339816

This should do it:

$('#main-menu li ul').each(function() {
    var $children = $(this).children('li');
    var count = children.length;
    if (count) {
        $children.css('width', 100 / count + '%');
    }
});

Upvotes: 0

Related Questions